Sub topic 8
Registering and resolving with get_it
This chapter covers the get_it package. You register how to build each dependency once, and you resolve it by type wherever you need it. It assumes you know Dart abstract classes, ChangeNotifier, and the idea of a composition root from earlier chapters. It also assumes you have read the service locator chapter. The three lifetimes get a short description here and are compared in the next chapter.
The two operations
get_it is a registry that maps a Dart type to a recipe for producing an object of that type. It has two operations:
- Register. Tell the registry how to produce a
T, usually at app startup. - Resolve. Ask the registry for a
Tand get back an instance.
Add the package with flutter pub add get_it. Then create one registry for the app. The package exposes a global singleton registry, and the usual convention is to keep it in a top-level variable:
import 'package:get_it/get_it.dart';
final getIt = GetIt.instance;GetIt.instance and GetIt.I return the same object. Every call site that uses getIt talks to one shared registry.
A complete example
This example reuses the repository and view model from earlier in the tutorial. It registers them, resolves the view model in a widget, and runs as a whole app.
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async {
// Call the real backend here.
return 'User $id';
}
}
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}
final getIt = GetIt.instance;
void setupLocator() {
getIt.registerLazySingleton<UserRepository>(() => ApiUserRepository());
getIt.registerFactory<ProfileViewModel>(
() => ProfileViewModel(getIt<UserRepository>()),
);
}
void main() {
setupLocator();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: ProfilePage());
}
}
class ProfilePage extends StatefulWidget {
const ProfilePage({super.key});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
late final ProfileViewModel _viewModel = getIt<ProfileViewModel>();
@override
void initState() {
super.initState();
_viewModel.load(1);
}
@override
void dispose() {
_viewModel.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ListenableBuilder(
listenable: _viewModel,
builder: (context, _) => Text(_viewModel.name ?? 'Loading...'),
),
),
);
}
}setupLocator() is the composition root for this app. Everything that decides which implementation is used lives in that one function. ProfileViewModel itself never mentions getIt. It receives its repository through its constructor, so it stays testable without the registry.
How registration works
registerLazySingleton<UserRepository>(() => ApiUserRepository()) has two parts that are easy to mix up:
- The type argument,
UserRepository, is the key. It is what callers will ask for. - The closure returns the value, here an
ApiUserRepository.
If you leave out the type argument, Dart infers it from the closure and the key becomes ApiUserRepository. Callers that ask for UserRepository would then fail. Always write the abstract type explicitly. This is the point of depending on abstractions, and it lets you swap the implementation in one place.
The three common registration methods
| Method | When the object is created | Instances returned |
|---|---|---|
| `registerSingleton<T>(instance)` | You build it before registering | The same one every time |
| `registerLazySingleton<T>(() => ...)` | On the first `getIt<T>()` call | The same one every time |
| `registerFactory<T>(() => ...)` | On every `getIt<T>()` call | A new one every time |
The next chapter explains how to choose among them. For now, note one rule. Anything with per-screen state, such as a view model, is usually a factory. Anything stateless and shareable, such as a repository, is usually a lazy singleton.
How resolution works
getIt<UserRepository>() is shorthand for getIt.get<UserRepository>(). The registry looks up the key, runs the factory or returns the stored instance, and returns it typed as UserRepository. Resolution is synchronous and does not need a BuildContext. That is the main difference from Provider, and it is also the source of most of get_it's problems.
Closures that call getIt<...>() inside a registration run at resolve time, not at registration time. This is why the factory above can ask for UserRepository even though the repository registration appears on the line above it. Registration order matters only for eager registerSingleton calls, which build their value on the spot.
Passing parameters to a factory
A view model often needs a runtime value, such as a user id. Do not read the id from a global. Register a parameterized factory instead:
void setupLocator() {
getIt.registerLazySingleton<UserRepository>(() => ApiUserRepository());
getIt.registerFactoryParam<ProfileViewModel, int, void>(
(userId, _) => ProfileViewModel(getIt<UserRepository>(), userId),
);
}
// Resolving:
final viewModel = getIt<ProfileViewModel>(param1: 42);This example assumes ProfileViewModel takes an int userId as a second constructor argument. The generic arguments are the type produced, the type of param1, and the type of param2. Use void for a parameter you do not need. A wrong parameter type fails at runtime, not at compile time, which is a real cost of this API.
Named registrations
Sometimes you need two implementations of one type, for example a cached repository and a live one. Give each an instanceName:
getIt.registerLazySingleton<UserRepository>(
() => ApiUserRepository(),
instanceName: 'live',
);
getIt.registerLazySingleton<UserRepository>(
() => CachedUserRepository(),
instanceName: 'cached',
);
final repo = getIt<UserRepository>(instanceName: 'cached');Names are plain strings, so typos are not caught until runtime. Prefer distinct abstract types when you can.
Dependencies that need async setup
Some objects need asynchronous work before use, such as opening a database. Register them with registerSingletonAsync and wait for all of them before you start the app:
import 'package:flutter/widgets.dart';
import 'package:get_it/get_it.dart';
class Database {
static Future<Database> open() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return Database();
}
}
final getIt = GetIt.instance;
Future<void> setupLocator() async {
getIt.registerSingletonAsync<Database>(() => Database.open());
await getIt.allReady();
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await setupLocator();
runApp(const SizedBox());
}allReady() completes when every async singleton has finished. If one depends on another, pass dependsOn: [OtherType] to registerSingletonAsync so get_it initializes them in the right order. Resolving an async singleton before it is ready throws.
Common errors
- Not registered. Resolving a type that was never registered fails with an assertion that says the object or factory of that type is not registered inside GetIt. The usual causes are a missing
setupLocator()call, registering the concrete type while resolving the abstract one, and resolving beforemain()has run setup. - Registered twice. Registering the same type and name again throws, which protects you from silent overrides. Hot restart keeps the registry in some setups, so a second
setupLocator()call can throw. Guard withif (!getIt.isRegistered<UserRepository>())or callgetIt.reset()at the start of setup during development. - Resolving in the wrong place. Calling
getIt<T>()deep inside business classes hides their dependencies. A reader can no longer see what a class needs from its constructor. Resolve in the composition root and in widgets that create view models, and pass objects down through constructors. - Leaked factory objects. A factory gives you a new object, but getit does not dispose it. Whoever resolved the object owns it. That is why `ProfilePageState
callsdispose()` on its view model.
Keeping tests safe
Because the registry is global, state leaks between tests unless you clear it. Reset it before each test and register fakes:
setUp(() {
getIt.reset();
getIt.registerLazySingleton<UserRepository>(() => FakeUserRepository());
});When a class takes its dependencies by constructor, you can skip the registry entirely and pass a fake directly. The testing chapter develops both styles.
Exercise
A teammate registers getIt.registerLazySingleton(() => ApiUserRepository()); and then resolves getIt<UserRepository>() in a widget. The app throws a "not registered" error. What is the cause, and how do you fix it?
Show answer
With no type argument, Dart infers the key from the closure's return type, so the key is ApiUserRepository, not UserRepository. The lookup for UserRepository finds nothing. Fix it by writing the abstract type explicitly: getIt.registerLazySingleton<UserRepository>(() => ApiUserRepository());.
Exercise
Why is ProfileViewModel registered with registerFactory while UserRepository uses registerLazySingleton, and who must dispose the view model?
Show answer
The view model holds per-screen state, so each screen needs its own instance, and a factory returns a new one per call. The repository is shared and stateless, so one lazily created instance is enough. get_it does not dispose factory-created objects, so the widget that resolved the view model must call dispose(), typically in its State.dispose.