Skip to content

Binding

A Binding acts as a configuration for how to create or provide a particular dependency. Bindings support:

  • Direct instance assignment (toInstance() — accepts a value or an already running Future)
  • Lazy providers (sync/async functions)
  • Provider functions supporting dynamic parameters
  • Named instances for resolving by string key
  • Optional singleton lifecycle
void builder(Scope scope) {
// Provide a direct instance
bind<String>().toInstance("Hello world");
// Provide an async direct instance (toInstance accepts FutureOr<T>)
bind<String>().toInstance(Future.value("Hello world"));
// Provide a lazy sync instance using a factory
bind<String>().toProvide(() => "Hello world");
// Provide a lazy async instance using a factory
bind<String>().toProvideAsync(() async => "Hello async world");
// Provide an instance with dynamic parameters (sync)
bind<String>().toProvideWithParams((params) => "Hello $params");
// Provide an instance with dynamic parameters (async)
bind<String>().toProvideAsyncWithParams((params) async => "Hello $params");
// Named instance for retrieval by name
bind<String>().toProvide(() => "Hello world").withName("my_string");
// Mark as singleton (only one instance within the scope)
bind<String>().toProvide(() => "Hello world").singleton();
}

Every bind<T>() must be completed with one of the targets above. bind<T>() on its own registers nothing that can be resolved, so installing such a module throws a StateError naming the type, the name (for a named binding) and the module:

class NetworkModule extends Module {
@override
void builder(Scope scope) {
bind<String>().withName('baseUrl'); // no target — never resolvable
}
}
scope.installModules([NetworkModule()]);
// StateError: Binding for `String` named 'baseUrl' in module NetworkModule has
// no target, so it can never be resolved. Complete it with toInstance(),
// toProvide(), toProvideWithParams(), toProvideAsync() or
// toProvideAsyncWithParams().