Skip to content

Instantly share code, notes, and snippets.

@crcdng
Last active February 22, 2020 03:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crcdng/e6f40cec68e178162247894abb8cadb8 to your computer and use it in GitHub Desktop.
Save crcdng/e6f40cec68e178162247894abb8cadb8 to your computer and use it in GitHub Desktop.
Dart Future example
import 'dart:async';
import 'dart:math';
void main() {
print("The main UI thread starts here.");
print("Now it will take 10 seconds to display news headlines.");
displayNews();
print("The main UI thread ends.");
}
void displayNews() {
Future<String> displayHeadlines = checkNews();
displayHeadlines.then((headline) {
print("Headlines: $headline");
}).catchError((error) {
print("An error ocurred: $error");
}).whenComplete(() {
print('complete');
});
}
Future<String> checkNews() {
return Future.delayed(Duration(seconds: 10), () {
if (Random().nextBool()) {
return "UFO LANDED, ALIEN GREETED, WORLD SAVED";
} else {
throw Error();
}
}).timeout(
Duration(seconds: 20),
onTimeout: () => "A timeout occurred",
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment