Skip to content

Instantly share code, notes, and snippets.

@RedBrogdon
Last active July 21, 2020 00:45
Show Gist options
  • Save RedBrogdon/88970173429a487e82caf8ccf949157e to your computer and use it in GitHub Desktop.
Save RedBrogdon/88970173429a487e82caf8ccf949157e to your computer and use it in GitHub Desktop.
Snippet 11: Late and lazy
// Here's another pattern that `late` can
// help with: lazy initialization for
// expensive non-nullable fields.
//
// Try running this code without changing
// it. What do you think will change if
// you make `_cache` a `late` field?
int _computeValue() {
print('Computing value...');
return 3;
}
class CachedValueProvider {
final _cache = _computeValue();
int get value => _cache;
}
void main() {
print('Calling constructor...');
var provider = CachedValueProvider();
print('Getting value...');
print('The value is ${provider.value}!');
}
// Fun fact: once you add `late` to the
// declaration of `_cache`, you can move
// the `_computeValue` function into the
// `CachedValueProvider` class and the
// code will still work! Initialization
// expressions for `late` fields can use
// instance methods in their initializers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment