Dependency injection

suggest change

Dependency injection (DI) means that an object gets the things it depends on (a database, an HTTP client, a clock, a logger) from the outside instead of creating them itself.

In practice it's mostly a matter of moving new SomeService() out of the class and into a constructor parameter. That small change gives you:

Dart needs no framework for this. This article covers:

The problem: hard-coded dependencies

This class creates its own dependencies:

import 'dart:io';

class OrderService {
  final _file = File('orders.log');

  void placeOrder(String item) {
    final now = DateTime.now();
    _file.writeAsStringSync('$now $item\n', mode: FileMode.append);
    print('ordered $item');
  }
}

void main() {
  OrderService().placeOrder('book');
}

Output:

ordered book

It works, but:

Constructor injection

The fix is to describe what OrderService needs with interfaces and receive implementations through the constructor. In Dart 3 an abstract interface class is the idiomatic way to declare a pure interface: it can be implemented, but not extended or instantiated.

abstract interface class OrderStore {
  void save(String line);
}

abstract interface class Clock {
  DateTime now();
}

class MemoryOrderStore implements OrderStore {
  final lines = <String>[];

  @override
  void save(String line) => lines.add(line);
}

class SystemClock implements Clock {
  const SystemClock();

  @override
  DateTime now() => DateTime.now();
}

class OrderService {
  final OrderStore _store;
  final Clock _clock;

  OrderService(this._store, this._clock);

  void placeOrder(String item) {
    _store.save('${_clock.now().toIso8601String()} $item');
    print('ordered $item');
  }
}

void main() {
  final store = MemoryOrderStore();
  final service = OrderService(store, const SystemClock());

  service.placeOrder('book');
  service.placeOrder('pen');
  print(store.lines.length);
}

Output:

ordered book
ordered pen
2

OrderService no longer knows whether lines go to memory, a file or PostgreSQL. Declaring the fields final makes the dependencies fixed for the lifetime of the object, which is almost always what you want. Initializing formals (this._store) keep the constructor short; see Constructors for more.

Every Dart class also defines an implicit interface, so you can implements a concrete class too. A dedicated interface is still clearer, and it means a fake doesn't have to implement private members.

Testing with fakes

With injected dependencies, a test can control everything. Fakes are usually tiny classes written for the test:

abstract interface class OrderStore {
  void save(String line);
}

abstract interface class Clock {
  DateTime now();
}

class OrderService {
  final OrderStore _store;
  final Clock _clock;

  OrderService(this._store, this._clock);

  void placeOrder(String item) {
    _store.save('${_clock.now().toIso8601String()} $item');
  }
}

// Test doubles: tiny classes written just for the test.
class FakeStore implements OrderStore {
  final saved = <String>[];

  @override
  void save(String line) => saved.add(line);
}

class FixedClock implements Clock {
  final DateTime time;
  FixedClock(this.time);

  @override
  DateTime now() => time;
}

void main() {
  final store = FakeStore();
  final clock = FixedClock(DateTime.utc(2026, 1, 2, 3, 4, 5));
  final service = OrderService(store, clock);

  service.placeOrder('book');

  final ok = store.saved.single == '2026-01-02T03:04:05.000Z book';
  print(store.saved);
  print(ok ? 'PASS' : 'FAIL');
}

Output:

[2026-01-02T03:04:05.000Z book]
PASS

The test is fast, deterministic and touches neither the disk nor the system clock. Packages like mocktail and mockito generate such doubles for you, but hand-written fakes are often simpler and easier to read.

Injecting functions

When a dependency has a single method, inject a function instead of an interface. A typedef gives the function type a name. Making the parameters optional with production defaults keeps call sites simple:

typedef Now = DateTime Function();
typedef Log = void Function(String message);

class Greeter {
  final Now _now;
  final Log _log;

  Greeter({Now? now, Log? log})
      : _now = now ?? DateTime.now,
        _log = log ?? print;

  void greet(String name) {
    final hour = _now().hour;
    final part = hour < 12 ? 'morning' : (hour < 18 ? 'afternoon' : 'evening');
    _log('Good $part, $name!');
  }
}

void main() {
  // Production: defaults are used.
  Greeter().greet('Alice');

  // Test: inject a fixed time and capture output.
  final captured = <String>[];
  final greeter = Greeter(
    now: () => DateTime(2026, 5, 1, 20, 0),
    log: captured.add,
  );
  greeter.greet('Bob');
  print('captured: $captured');
}

Output (the first line depends on when you run it):

Good evening, Alice!
captured: [Good evening, Bob!]

Note the tear-offs: DateTime.now, print and captured.add are passed as function values without calling them.

Defaults are convenient for small dependencies like clocks and loggers. For heavy ones (database connections, HTTP clients) prefer required parameters, so a forgotten argument is a compile-time error rather than a production connection opened in a test.

The composition root

If classes no longer create their dependencies, something has to. The usual answer is a single composition root near main() that creates all the objects and wires them together. It's the only place that knows the concrete types.

late final fields with initializers make a neat, dependency-free container: each object is created on first access, at most once, and the field order doesn't matter.

class Config {
  final String dbUrl;
  final bool verbose;
  const Config({required this.dbUrl, required this.verbose});
}

class Logger {
  final bool verbose;
  Logger(this.verbose);
  void debug(String msg) {
    if (verbose) print('[debug] $msg');
  }
}

class Database {
  final String url;
  final Logger log;
  Database(this.url, this.log) {
    log.debug('connecting to $url');
  }
  Future<void> close() async => log.debug('closing $url');
}

class UserRepository {
  final Database db;
  UserRepository(this.db);
  String findName(int id) => 'user$id';
}

class UserService {
  final UserRepository repo;
  final Logger log;
  UserService(this.repo, this.log);

  String describe(int id) {
    log.debug('describe($id)');
    return 'User #$id is ${repo.findName(id)}';
  }
}

/// The composition root: the only place that knows concrete types
/// and how they are wired together.
class App {
  final Config config;
  late final Logger logger = Logger(config.verbose);
  late final Database database = Database(config.dbUrl, logger);
  late final UserRepository users = UserRepository(database);
  late final UserService userService = UserService(users, logger);

  App(this.config);

  Future<void> dispose() => database.close();
}

Future<void> main() async {
  final app = App(const Config(dbUrl: 'postgres://localhost/app', verbose: true));
  print('app created');
  print(app.userService.describe(7));
  print(identical(app.logger, app.userService.log));
  await app.dispose();
}

Output:

app created
[debug] connecting to postgres://localhost/app
[debug] describe(7)
User #7 is user7
true
[debug] closing postgres://localhost/app

The database connection isn't opened until userService is first used, and logger is shared because a late final field is computed only once. The App class is plain Dart: if a dependency is missing or has the wrong type, the compiler tells you.

For most command-line tools and servers, this manual wiring is all the "DI framework" you need.

A hand-written service locator

A service locator is a registry that objects ask for their dependencies by type. It's less explicit than constructor injection (a class's needs are hidden in its body), but it's popular in Flutter apps where passing objects down a deep widget tree is tedious.

Because Dart generics are reified, a type argument T can be used as a map key at runtime. That makes a basic locator a few lines long:

class ServiceLocator {
  final _factories = <Type, Object Function()>{};
  final _instances = <Type, Object>{};

  /// A single instance, created immediately.
  void singleton<T extends Object>(T instance) => _instances[T] = instance;

  /// A single instance, created on first use.
  void lazySingleton<T extends Object>(T Function() create) {
    _factories[T] = () => _instances.putIfAbsent(T, create);
  }

  /// A new instance on every lookup.
  void factory<T extends Object>(T Function() create) => _factories[T] = create;

  T get<T extends Object>() {
    final instance = _instances[T] ?? _factories[T]?.call();
    if (instance == null) {
      throw StateError('No registration for $T');
    }
    return instance as T;
  }
}

class Counter {
  static var created = 0;
  final int id = ++created;
}

class Request {
  static var created = 0;
  final int id = ++created;
}

void main() {
  final sl = ServiceLocator()
    ..singleton<String>('my-app')
    ..lazySingleton<Counter>(Counter.new)
    ..factory<Request>(Request.new);

  print(sl.get<String>());
  print('counters created before get: ${Counter.created}');
  print(identical(sl.get<Counter>(), sl.get<Counter>()));
  print('counters created: ${Counter.created}');
  print('${sl.get<Request>().id} ${sl.get<Request>().id}');

  try {
    sl.get<double>();
  } on StateError catch (e) {
    print(e.message);
  }
}

Output:

my-app
counters created before get: 0
true
counters created: 1
1 2
No registration for double

This shows the three lifetimes every DI container offers: singleton (one eager instance), lazy singleton (one instance created on first use) and factory (a new instance per lookup). Counter.new is a constructor tear-off.

The big drawback is visible on the last line: a missing registration is a runtime error, not a compile error.

The get_it package

get_it is the most widely used service locator for Dart and Flutter. Add it with:

dart pub add get_it

This article uses get_it 9.3.0.

Registering and retrieving

GetIt.instance is a global locator. Register implementations under their interface type, then retrieve them with get<T>() or by calling the instance directly:

import 'package:get_it/get_it.dart';

final getIt = GetIt.instance;

abstract interface class WeatherApi {
  double temperature(String city);
}

class FakeWeatherApi implements WeatherApi {
  FakeWeatherApi() {
    print('FakeWeatherApi created');
  }

  @override
  double temperature(String city) => city.length * 3.0;
}

class WeatherReport {
  final WeatherApi api;
  final String city;
  WeatherReport(this.api, this.city);

  String render() => '$city: ${api.temperature(city)} C';
}

void setup() {
  getIt.registerLazySingleton<WeatherApi>(FakeWeatherApi.new);
  getIt.registerFactoryParam<WeatherReport, String, void>(
    (city, _) => WeatherReport(getIt<WeatherApi>(), city),
  );
}

void main() {
  setup();
  print('setup done');

  final paris = getIt<WeatherReport>(param1: 'Paris');
  final oslo = getIt.get<WeatherReport>(param1: 'Oslo');
  print(paris.render());
  print(oslo.render());
  print(identical(paris.api, oslo.api));
  print(getIt.isRegistered<WeatherApi>());
}

Output:

setup done
FakeWeatherApi created
Paris: 15.0 C
Oslo: 12.0 C
true
true

Always pass the type argument explicitly (registerLazySingleton<WeatherApi>). Without it, the type is inferred from the factory as FakeWeatherApi, and getIt<WeatherApi>() fails at runtime.

Notice that WeatherReport itself still uses constructor injection: only the setup code talks to getIt. Keeping locator calls at the edges keeps the rest of your classes easy to test without get_it.

The main registration methods:

Method Lifetime
registerSingleton<T>(instance) one instance, created by you up front
registerLazySingleton<T>(factory) one instance, created on first get
registerFactory<T>(factory) new instance on every get
registerFactoryParam<T, P1, P2>(factory) new instance, with up to two runtime parameters
registerSingletonAsync<T>(asyncFactory) one instance from an async factory, started immediately
registerSingletonWithDependencies<T>(factory, dependsOn:) one instance, created when its dependencies are ready

Async initialization and disposal

Many services need async setup: reading a config file, opening a database. registerSingletonAsync starts the factory right away, dependsOn orders the startup, and allReady() waits for everything:

import 'package:get_it/get_it.dart';

final getIt = GetIt.instance;

class Config {
  final String apiUrl;
  Config(this.apiUrl);

  static Future<Config> load() async {
    await Future.delayed(const Duration(milliseconds: 50));
    print('config loaded');
    return Config('https://api.example.com');
  }
}

class Database {
  final String name;
  Database(this.name);

  static Future<Database> open() async {
    await Future.delayed(const Duration(milliseconds: 20));
    print('database opened');
    return Database('app.db');
  }

  Future<void> close() async => print('database closed');
}

class ApiClient {
  final Config config;
  final Database db;
  ApiClient(this.config, this.db) {
    print('ApiClient created');
  }
}

Future<void> main() async {
  getIt.registerSingletonAsync<Config>(Config.load);
  getIt.registerSingletonAsync<Database>(
    Database.open,
    dispose: (db) => db.close(),
  );
  getIt.registerSingletonWithDependencies<ApiClient>(
    () => ApiClient(getIt<Config>(), getIt<Database>()),
    dependsOn: [Config, Database],
  );

  await getIt.allReady();
  print('all ready');

  final client = getIt<ApiClient>();
  print('${client.config.apiUrl} ${client.db.name}');

  await getIt.reset(); // calls dispose functions
}

Output:

database opened
config loaded
ApiClient created
all ready
https://api.example.com app.db
database closed

Config and Database initialize concurrently (the database finishes first because it's faster), and ApiClient is created only after both are done. reset() unregisters everything and calls the dispose callbacks, so resources are released in one place.

Scopes

A scope is a layer of registrations pushed on top of the existing ones. Registrations in the new scope shadow older ones until the scope is popped. This fits things with a limited lifetime, like a logged-in user session:

import 'package:get_it/get_it.dart';

final getIt = GetIt.instance;

abstract interface class Auth {
  String get user;
}

class GuestAuth implements Auth {
  @override
  String get user => 'guest';
}

class LoggedInAuth implements Auth {
  @override
  final String user;
  LoggedInAuth(this.user);
}

Future<void> main() async {
  getIt.registerSingleton<Auth>(GuestAuth());
  print(getIt<Auth>().user);

  getIt.pushNewScope(
    scopeName: 'session',
    init: (scope) => scope.registerSingleton<Auth>(LoggedInAuth('alice')),
  );
  print(getIt<Auth>().user);
  print(getIt.currentScopeName);

  await getIt.popScope();
  print(getIt<Auth>().user);
}

Output:

guest
alice
session
guest

popScope() disposes everything registered in that scope, so logging out also cleans up session objects.

Testing with get_it

Because GetIt.instance is global, tests must reset it between test cases. Register fakes in setUp and call reset() in tearDown:

import 'package:get_it/get_it.dart';
import 'package:test/test.dart';

abstract interface class UserApi {
  Future<String> fetchName(int id);
}

class GreetingService {
  final UserApi api;
  GreetingService(this.api);

  Future<String> greet(int id) async => 'Hello, ${await api.fetchName(id)}!';
}

class FakeUserApi implements UserApi {
  final requested = <int>[];

  @override
  Future<String> fetchName(int id) async {
    requested.add(id);
    return 'Test User';
  }
}

final getIt = GetIt.instance;

void main() {
  late FakeUserApi fake;

  setUp(() {
    fake = FakeUserApi();
    getIt.registerSingleton<UserApi>(fake);
    getIt.registerFactory(() => GreetingService(getIt<UserApi>()));
  });

  tearDown(() => getIt.reset());

  test('greets the user returned by the API', () async {
    final service = getIt<GreetingService>();
    expect(await service.greet(42), 'Hello, Test User!');
    expect(fake.requested, [42]);
  });

  test('constructor injection needs no container at all', () async {
    final service = GreetingService(FakeUserApi());
    expect(await service.greet(1), 'Hello, Test User!');
  });
}

Run it with dart test and both tests pass. The second test makes the point of this article: when a class takes its dependencies through the constructor, the test doesn't need the container at all. If you'd rather not touch the global instance, GetIt.asNewInstance() creates an independent locator you can pass around.

Generating many similar test cases is covered in Parameterized tests.

Zone-scoped dependencies

Some dependencies are used almost everywhere, like the current time or the active locale, and threading them through every constructor is noisy. Dart's Zones can carry values that are visible to all code running inside the zone, including across awaits.

The official clock package uses this for time. Code reads clock.now() instead of DateTime.now(), and tests override it with withClock:

import 'package:clock/clock.dart';

String trialStatus(DateTime trialEnd) {
  final left = trialEnd.difference(clock.now()).inDays;
  return left > 0 ? '$left days left' : 'trial expired';
}

void main() {
  final end = DateTime(2026, 3, 15);

  withClock(Clock.fixed(DateTime(2026, 3, 1)), () {
    print(trialStatus(end));
  });

  withClock(Clock.fixed(DateTime(2026, 4, 1)), () {
    print(trialStatus(end));
  });
}

Output:

14 days left
trial expired

You can build the same mechanism for your own dependencies with runZoned and zoneValues:

import 'dart:async';

abstract interface class Translator {
  String tr(String key);
}

class English implements Translator {
  const English();
  @override
  String tr(String key) => key;
}

class Polish implements Translator {
  const Polish();
  static const _words = {'hello': 'cześć', 'bye': 'pa'};
  @override
  String tr(String key) => _words[key] ?? key;
}

// Private key object, so other code can't clash with it.
final _translatorKey = Object();

Translator get translator =>
    Zone.current[_translatorKey] as Translator? ?? const English();

R withTranslator<R>(Translator t, R Function() body) =>
    runZoned(body, zoneValues: {_translatorKey: t});

void greet() => print(translator.tr('hello'));

Future<void> main() async {
  greet();
  withTranslator(const Polish(), greet);

  await withTranslator(const Polish(), () async {
    await Future.delayed(const Duration(milliseconds: 10));
    greet(); // zone values survive across awaits
  });
}

Output:

hello
cześć
cześć

Use this sparingly. Zone values are implicit, like globals, so they're best reserved for cross-cutting concerns such as time, locale, or a request ID used for Logging.

Choosing an approach

There are also code-generating DI tools. injectable generates get_it registration code from annotations like @lazySingleton, and in Flutter, provider and riverpod combine dependency injection with state management.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents