Last active
February 22, 2020 03:59
-
-
Save crcdng/e6f40cec68e178162247894abb8cadb8 to your computer and use it in GitHub Desktop.
Dart Future example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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