Dart Dependency Injection in 2026: get_it vs injectable vs kiwi

Your Flutter app started with three services passed down through constructors. Eighteen months later the widget tree is nine levels deep, every new screen needs the same auth repository, and someone has started importing a global final apiClient = ApiClient() just to make the build pass. That global is the actual bug: it cannot be swapped in tests, it initialises before the token is loaded, and it keeps a stale http.Client alive across hot restarts.

A dependency container fixes this — but Dart has three very different answers to the same problem, and they disagree about almost everything: whether the container resolves at runtime or at compile time, whether you write registrations by hand or generate them, and whether lookups are a Map access or a generated constructor call. Picking the wrong one costs you either a code generation pipeline you did not need or a pile of manual registration code that drifts out of sync with your classes.

TL;DR — Quick Verdict

Pick get_it if you want zero code generation and full control — it is the de facto standard, a 1,476-star MIT-licensed service locator maintained under the fluttercommunity organisation, and its API has barely changed in five years. Pick injectable if you already use get_it and are tired of hand-writing registrations — it is a 627-star code generator that writes the get_it calls for you from annotations. Pick kiwi if you want a small explicit container with scoped containers and no global singleton — 347 stars, a Map-backed container, and compile-time generated wiring on top.

Short version: get_it alone is enough for 80% of apps. Add injectable when registration boilerplate exceeds ~30 lines. Choose kiwi when you specifically need multiple scoped containers — that is its one structural advantage.

Side-by-Side Comparison

Dimensionget_itinjectablekiwi
ApproachRuntime service locatorCode generator for get_itRuntime IoC container + optional generator
GitHub stars1,476627347
Last push2026-09-292026-08-132026-08-17
LicenseMITMITMIT
Code generationNoneRequired (build_runner or lean_builder)Optional (kiwi_generator)
Lookup mechanismMap access, O(1)Map access (generated)Map access
Scoped containersYes (named scopes)Inherits from get_itYes, first-class (KiwiContainer.scoped())
Async registrationregisterSingletonAsync@preResolveManual (registerInstance after await)
Test resetgetIt.reset()getIt.reset()New KiwiContainer.scoped()
Learning curveLowMedium (annotations + generator)Medium (container API)
Maintained byfluttercommunityMilad Akariegbtb16

The star gap is not a quality gap. It reflects audience: get_it is the default in most Flutter templates and tutorials, so it accumulates stars by default. kiwi solves a narrower problem — scoped containers — and has a correspondingly smaller audience.

Decision Matrix: Use Case → Tool

Your situationUseWhy
New Flutter app, 5–20 servicesget_itNo generator, no build step, register in one function
Large app, 40+ injectable classesinjectableAnnotations keep registrations next to the class they describe
Multi-tenant or multi-session appkiwiKiwiContainer.scoped() gives each session its own graph
Testing-heavy codebaseget_itreset() plus registerSingleton overrides is the simplest test seam
Pure Dart CLI or serverget_itNo Flutter dependency, works in dart run and compiled binaries
Team strongly prefers annotationsinjectableRegistrations become part of the class, not a distant file
You need compile-time verification of the graphkiwiGenerated wiring fails at build time, not at first lookup

get_it — The Service Locator That Won by Default

get_it is deliberately dumb: a global registry keyed by type, with three lifetimes. There is no reflection, no generator, and no magic — which is exactly why it survives Dart version bumps without breaking.

1
2
dependencies:
  get_it: ^8.0.2

The official quick start is three steps — define, register, access:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import 'package:get_it/get_it.dart';

final getIt = GetIt.instance;

class ApiClient {
  Future<void> fetchData() async { /* ... */ }
}

class UserRepository {
  final ApiClient apiClient;
  UserRepository(this.apiClient);
}

void configureDependencies() {
  getIt.registerSingleton<ApiClient>(ApiClient());
  getIt.registerLazySingleton<UserRepository>(
    () => UserRepository(getIt<ApiClient>()),
  );
}

// From anywhere — no BuildContext, no constructor threading:
final repo = getIt<UserRepository>();

The lifetime decision is where real projects get burned:

  • registerSingleton — constructed immediately at registration time. If the constructor does network I/O or reads SharedPreferences, you are doing async work in main() before runApp, and anything that depends on it will see a half-initialised object.
  • registerLazySingleton — constructed on first lookup. This is the right default for most services because it avoids paying startup cost for code paths the user never touches.
  • registerFactory — a new instance per lookup. Correct for short-lived objects such as form controllers or request-scoped clients; catastrophic if you use it for a cache.

For services that must load a token before the UI appears, use the async variant and await it during startup:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
void configureDependencies() {
  getIt.registerSingletonAsync<AuthStore>(() async {
    final store = AuthStore();
    await store.restoreSession();
    return store;
  });
  getIt.registerLazySingleton<UserRepository>(
    () => UserRepository(getIt<ApiClient>(), getIt<AuthStore>()),
  );
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  configureDependencies();
  await getIt.allReady();   // resolves every async registration
  runApp(const App());
}

await getIt.allReady() is the single most important line in a get_it app with async dependencies. Without it, the first widget that resolves AuthStore synchronously gets a StateError — and the stack trace points at the widget, not at the missing await.

Test isolation is a one-liner, which is why teams stay:

1
2
3
4
setUp(() {
  getIt.reset();
  getIt.registerSingleton<ApiClient>(FakeApiClient());
});

reset() disposes singletons that were registered with a dispose callback and clears every registration. If you forget it, state leaks between tests and the failure surfaces three files away from the cause.

injectable — Annotations Instead of a Registration File

injectable does not replace get_it; it generates code that calls it. You annotate classes, run a builder, and get a .config.dart file containing the same registerSingleton calls you would have written by hand.

1
2
3
4
5
6
7
dependencies:
  get_it:
  injectable:

dev_dependencies:
  injectable_generator:
  build_runner:

Setup follows the official four-step flow: define the global GetIt instance, annotate a top-level configureDependencies function with @InjectableInit, import the generated file, and call the generated init() extension:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import 'di.config.dart';

final getIt = GetIt.instance;

@InjectableInit(
  initializerName: 'init',
  preferRelativeImports: true,
  asExtension: true,
)
void configureDependencies() => getIt.init();

Individual services are marked at the class:

1
2
3
4
5
6
7
8
@lazySingleton
class ApiClient {}

@injectable
class UserRepository {
  final ApiClient apiClient;
  UserRepository(this.apiClient);
}

Then regenerate:

1
dart run build_runner build --delete-conflicting-outputs

The 2026 detail that matters: injectable now supports lean_builder as a faster alternative to build_runner. Add it to dev_dependencies and run dart run lean_builder build (or watch), and disable the build_runner builder in build.yaml if you want to avoid running both. On a medium Flutter app this cuts codegen from tens of seconds to a couple of seconds per change — enough to change how often you actually run it.

The trade-off is honest: you gain annotation locality and lose the ability to see the whole object graph in one file. When a lookup fails at runtime with “Object/factory with type X is not registered inside GetIt”, the fix is usually that the class is missing @injectable, or the file was not re-imported into the module that the generator scans. Debugging a generated graph is slower than reading 40 hand-written lines.

kiwi — Explicit Containers and Real Scopes

kiwi is the smallest of the three conceptually: a KiwiContainer backed by a Map, with instances, factories, and named registrations. No reflection — the documentation is explicit that lookups are plain map access, so cost is predictable.

1
2
dependencies:
  kiwi: ^latest_version

Manual registration looks like this:

1
2
3
4
5
6
7
8
9
import 'package:kiwi/kiwi.dart';

final container = KiwiContainer();

container.registerInstance(ApiClient());
container.registerInstance<Character>(Sith('Anakin', 'Skywalker'), name: 'DartVader');
container.registerFactory((c) => UserRepository(c.resolve<ApiClient>()));

final repo = container.resolve<UserRepository>();

Two properties distinguish it from get_it:

  1. KiwiContainer.scoped() creates an independent container. In a multi-account app — one container per signed-in tenant, torn down on logout — this is a structural answer rather than a naming convention. With get_it you achieve the same with named scopes, but scopes are an advanced feature most teams never enable.
  2. Registration is explicit by type. registerInstance<Character>(Sith(...)) registers a subtype under a supertype, which makes “program to an interface” wiring readable at the call site.

With kiwi_generator, annotations and constructor injection remove most of the manual registration, and the generated wiring is verified at build time — a missing dependency becomes a compile error instead of a runtime StateError. That is a genuine advantage over both alternatives, at the cost of one more generator in your build.

1
2
3
4
5
6
dependencies:
  kiwi:

dev_dependencies:
  kiwi_generator:
  build_runner:

Pitfalls That Actually Bite

Registering a Factory for something stateful. A factory returns a new instance each lookup. If two widgets each resolve a “session” and each gets a fresh object, one writes a token the other never sees. Use Singleton or LazySingleton for anything holding state, and reserve factories for disposable per-screen objects.

Registration order with lazy singletons is not free. With registerLazySingleton, the factory body runs on first access. If that body resolves another lazy singleton which in turn depends on an async registration that has not completed, you get an intermittent failure that only appears on cold start with a slow disk. Await allReady() before runApp, and keep async dependencies at the leaves of the graph.

Forgetting reset() between tests. The failure mode is not a clean error — it is a test that passes in isolation and fails in the suite because a previous test left a real ApiClient registered. Put reset() in setUp, not tearDown; a crash mid-test then cannot leak state forward.

Codegen drift after a rename. Both injectable and kiwi_generator emit .config.dart / .g.dart files. If you rename a class and forget to regenerate, the old registration stays and the new type is unregistered. Add the generated files to your diff review, and run codegen in CI so a stale file fails the build rather than production.

Treating the container as a global variable. The container is a tool for wiring, not a licence to call getIt<Database>() from inside a widget’s build. Resolve once in the constructor or in a provider and pass the dependency down; resolving inside build hides the dependency from readers and makes widget tests need the whole container.

Assuming get_it is Flutter-only. It is not — the package explicitly supports pure Dart, server-side and CLI use. The same registration code works in a dart run script, which makes it useful for sharing wiring between a Flutter client and a Dart backend.

Migration and Coexistence Strategies

The practical migration path is one-directional and incremental. From hand-passed constructors to get_it: register only the services currently threaded through three or more constructors, leave everything else alone, and delete constructor parameters as screens are touched.

From get_it to injectable: do not rewrite the registration file in one commit. Keep configureDependencies() as the entry point, move the ten most-touched classes to annotations, and let the generator own the rest over several pull requests. Both can coexist in the same function — generated init() plus a handful of manual registerSingleton calls is a normal end state.

From get_it to kiwi: this is a real rewrite, because the lookup API differs (getIt<T>() versus container.resolve<T>()). Do it only if scoped containers are a product requirement. Migrating “because kiwi looks cleaner” trades a working graph for a week of churn.

Whichever you choose, keep the container behind your own thin facade for the services that matter. A ServiceRegistry class with typed getters means swapping the container later touches one file, not two hundred widget files. For the same reason, pin your serialization layer deliberately — the same codegen decisions apply, as covered in our Dart serialization comparison, and your HTTP layer deserves the same review we gave Dart HTTP clients. If you are coming from another ecosystem, the trade-offs in our TypeScript DI container comparison map almost one-to-one onto these three Dart options.

FAQ

Is get_it still maintained in 2026? Yes. The repository lives under the fluttercommunity organisation, was last pushed in September 2026, and the current major line is 8.x. The API is intentionally stable, so a long gap between releases reflects maturity rather than abandonment.

Do I need injectable if I use get_it? No. injectable is optional tooling that generates get_it registration code from annotations. Add it when manual registration passes roughly 30 lines or when classes are added faster than the registration file is updated. Below that threshold, the generator adds build complexity without saving meaningful time.

Can kiwi replace get_it entirely? Yes for most apps, but only migrate if you need what kiwi does better: independent scoped containers, explicit supertype registration, and compile-time verification through kiwi_generator. Otherwise you are trading a large, well-documented ecosystem for a smaller one with no functional gain.

How do I test code that uses a service locator? Reset the container in setUp, then register fakes for the types under test. With get_it that is getIt.reset() followed by registerSingleton<ApiClient>(FakeApiClient()). With kiwi, create a fresh KiwiContainer.scoped() per test so tests cannot share state at all.

Does dependency injection slow down Flutter apps? Not measurably at these scales. Both get_it and kiwi are Map lookups — constant time, no reflection. The real performance risk is registering stateful services as factories, which causes repeated construction and connection churn, not the lookup itself.

Can I use these libraries in a pure Dart backend instead of Flutter? Yes. get_it and kiwi both work without Flutter, and injectable generates plain Dart code. The main adjustment is lifecycle: a server process usually wants one long-lived container created at startup and disposed on shutdown, rather than the per-app-launch pattern used in mobile clients.


💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com