Skip to content

Instantly share code, notes, and snippets.

@wyattbiker
Created May 8, 2019 16:08
Show Gist options
  • Save wyattbiker/30d1cc674e4c4369041dfbbd1323c5b2 to your computer and use it in GitHub Desktop.
Save wyattbiker/30d1cc674e4c4369041dfbbd1323c5b2 to your computer and use it in GitHub Desktop.
futures examples
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
Future<void> printDailyNewsDigest() async {
var newsDigest = await gatherNewsReports();
print(newsDigest);
}
main() {
print('Start of app');
printSomething();
printDailyNewsDigest();
printWinningLotteryNumbers();
printWeatherForecast();
printBaseballScore();
}
printSomething() {
print('continue with other news');
// This blocks without await
// var list= await List<int>.generate(10000000, (int index) => index * index);
// print('list ${list[10]}');
var future=() async {
return await List<int>.generate(1000000, (int index) => index * index);
};
future().then((l){
print(l[10]);
print('Got the news');
});
// Future.delayed(Duration(seconds: 10), () => print("5678"));
// print('end');
}
printWinningLotteryNumbers() {
print('Winning lotto numbers: [23, 63, 87, 26, 2]');
}
printWeatherForecast() {
print("Tomorrow's forecast: 70F, sunny.");
}
printBaseballScore() {
print('Baseball score: Red Sox 10, Yankees 0');
}
const news = '<gathered news goes here>';
const oneSecond = Duration(seconds: 1);
// Imagine that this function is more complex and slow. :)
Future<String> gatherNewsReports() =>
Future.delayed(oneSecond, () => news);
// Alternatively, you can get news from a server using features
// from either dart:io or dart:html. For example:
//
// import 'dart:html';
//
// Future<String> gatherNewsReportsFromServer() => HttpRequest.getString(
// 'https://www.dartlang.org/f/dailyNewsDigest.txt',
// );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment