Async and Await
suggest changeimport 'dart:async';
Future<void> main() async {
var value = await _waitForValue();
print("Here is the value: $value");
// _waitForValue() returns a Future immediately. Without await you do not have the result yet.
var errorValue = "not finished yet";
_waitForValue();
print("Here is the error value: $errorValue"); // not finished yet
}
Future<int> _waitForValue() => new Future(() {
var n = 100000000;
// Do some long process
for (var i = 1; i <= n; i++) {
// Print out progress:
if ([n / 2, n / 4, n / 10, n / 20].contains(i)) {
print("Not done yet...");
}
// Return value when done.
if (i == n) {
print("Done.");
return i;
}
}
return n;
});
See example on Dartpad: https://dartpad.dartlang.org/11d189b51e0f2680793ab3e16e53613c
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents