Skip to content

Instantly share code, notes, and snippets.

@pulyaevskiy
Last active March 30, 2017 04:45
Show Gist options
  • Save pulyaevskiy/ef0bfff78d1cee2b22515f5f9eff2644 to your computer and use it in GitHub Desktop.
Save pulyaevskiy/ef0bfff78d1cee2b22515f5f9eff2644 to your computer and use it in GitHub Desktop.
Efficient Dart
import 'dart:async';
void main() {
// We retrieve boolean value 3 times in the for-loop below and print it.
for (var i = 1; i <= 3; i++) {
print('Printing "$value" $i time.');
}
}
/// Internal cache for our value.
bool _value;
/// Public getter for our value.
/// If there is no cached value we fetch it from `_getValueAsync`
/// and update the cache.
bool get value {
if (_value == null) {
_getValueAsync().then((_) {
print('Setting value to $_');
_value = _;
});
}
return _value;
}
// Assume to get our value we need to ask some external service.
// For simplicity here we just return a Future which gives us
// the same effect.
Future<bool> _getValueAsync() => new Future.value(true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment