Scope

Scope provides Inversion of Control using the dependency injection (DI) pattern for Dart applications.

Scope allows you to inject values into a scope and then 'use' those dependencies from any method (or constructor) called within that scope.

Scope provides DI for your call stack.

This is most easily understood via an example:

import 'package:scope/scope.dart';

/// create a key to access a scoped value
final ageKey = ScopeKey<int>();

void main() {
    /// create a Scope
    Scope()
    
    /// inject a value
    ..value<int>(ageKey, 18)
    
    /// run some code within the Scope
    ..run(() => a();
}
void a() => b();

/// `use` the injected value by its key 'ageKey'
void b() => print('You are ${use(ageKey)} years old');

We create a Scope within main and call the method a() which calls b(). Both a() and b() are within the declared scope and therefore have access to the injected value ageKey.

To access an injected value you call the use method.

Last updated