Sub topic 2
Providing dependencies through the widget tree
This chapter assumes you know Dart abstract classes, Flutter widgets, BuildContext, and ChangeNotifier. It covers how to make a dependency available to a whole subtree of widgets, how the Provider package does this, and how get_it works as a service locator.
Providing dependencies through the widget tree
Flutter passes data down the widget tree. A widget higher in the tree can expose an object, and any descendant can read it through its BuildContext. Use this to supply a repository once, near the top of the app, instead of constructing it in every screen.
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'User $id';
}Dependency injection with Provider
The Provider package wraps InheritedWidget so the code is shorter. Provider<T> creates a value once and makes it available to its child. A descendant reads it with context.read<T>(), which does not rebuild the widget when the value changes.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
Provider<UserRepository>(
create: (_) => ApiUserRepository(),
child: const MaterialApp(home: ProfileScreen()),
),
);
}
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
@override
Widget build(BuildContext context) {
final repository = context.read<UserRepository>();
return Scaffold(body: Text('Repository: ${repository.runtimeType}'));
}
}The service locator pattern
A service locator is a global registry. Code asks it for an object by type instead of receiving that object through a constructor. This removes the need to pass values down the tree, but every caller depends on the registry itself.
Registering and resolving with get_it
get_it is a Dart service locator. You register a factory function for a type, then resolve the type anywhere with getIt<T>().
import 'package:get_it/get_it.dart';
final getIt = GetIt.instance;
void setupLocator() {
getIt.registerLazySingleton<UserRepository>(() => ApiUserRepository());
}
Future<void> main() async {
setupLocator();
final name = await getIt<UserRepository>().fetchName(1);
print(name); // User 1
}> The lazy singleton is created on first use and then reused. Use registerFactory when each request should receive a new instance.
Exercise
In the get_it example, getIt<UserRepository>() is called twice in different screens. Does each call create a new ApiUserRepository?
Show answer
No. registerLazySingleton creates the instance on the first call and returns the same instance afterward.