Nesting

Scopes can be nested with the same keys or different keys injected at each level.

When you inject a key/value pair into a nested Scoped and then call use, the value from the closest Scope with a matching key is used.

If the key isn't in the immediate Scope we search up through parent scopes.

import 'package:scope/scope.dart';
void main() {

  // parent scope
  Scope()
    ..value<String>(greetingKey, 'Hello')
    ..value<int>(emphasisKey,  1)
     ..run(() {
    
          /// Nest child Scope (1)
          Scope()
          ..value<String>(greetingKey, 'Good day')
          ..run(() {
               Greeter().greet('Philipp'); // 'Good day, Philipp!'
          });

         /// Sibling of (1) = also nested witin the parent scope
         Scope()
          ..value<int>(emphasisKey, 3)
          ..run(() {
               Greeter().greet('Paul'); // 'Hello, Paul!!!'
         });
  });
}

There is no limit to the level of nesting that can be used.

Last updated