scope
Search…
Single and Sequence factories
Scope allows you to define values based on factory methods (callbacks) as a single value or a sequence of values.

Single

A single value is simply a value that is provided by making a call to a function rather than providing a fixed value.
import 'package:scope/scope.dart';
Scope()
..value<String>(nameKey, 'brett')
..value<DateTime>(dobKey, DateTime(year: 2000, month: 1, day 1))
..single<String>(ageKey, () => DateTime.now().difference(use(dobKey)).inYears) // called only once.
..run(() {
print('age: ${use(ageKey)}');
});
The call to single in the above example takes two arguments:
  • ScopeKey - ageKey
  • Factory method - () => DateTime.now().difference(use(dobKey)).inYears

Evaluation

The single value is calculated once by calling the factory method when the run method is called. The calculated factory value is then fixed for the life of the Scope.
You can think of this as eager evaluation of the factory method.
Factory methods have access to other 'in Scope' variables where as the value call does not.
The factory method can use other values declared in the same scope (or a parent scope). This is the main difference between the single call on line 4 and the value call on line 3. Both call functions but the factory method has access to other 'in Scope' variables where as the value call does not.
Be careful to avoid circular dependencies!

sequence

A sequence value is injected in a similar way to the single value. The difference is that the sequence method is NOT called when the run method is called but each time the use method is called with the sequence's ScopeKey.
import 'package:scope/scope.dart';
Scope()
..value<String>(nameKey, 'brett')
..value<DateTime>(dobKey, DateTime(year: 2000, month: 1, day 1)
..sequence<String>(ageKey, () => DateTime.now().difference(use(dobKey)).inYears) // called each time `use(ageKey)` is called within this Scope.
..run(() {
print('age: ${use(ageKey)}');
});
You can think of this as lazy evaluation of the sequence value.
A sequence can be used to recalculate a value each time it is used and could be used to provide a sequence of values (such as a counter or a random number generator).
Copy link
Outline
Single
sequence