异步返回String,延迟2s
Future<String> _fetchUserOrder() {
return Future.delayed(Duration(seconds: 2), () {
return "Large Latte";
});
}
//直接返回
String _createOrderMessage() {
var order = _fetchUserOrder();
return "Your order is: $order";
}
main(){
print("${_createOrderMessage()}");
}
//打印结果
flutter: Your order is: Instance of 'Future<String>'
Future<String> _createAsyncOrderMessage() async {
var order = await _fetchUserOrder();
return "Your order is: $order";
}
main() async {
print(await _createAsyncOrderMessage())
}
//2s后打印结果
flutter: Your order is: Large Latte
Future<void> _printOrderMessage() async {
print('Awaiting user ordr ...');
var order = await _fetchUserOrder();
print('your order is : $order');
}
_countSeconds(int s) {
for (var i = 0; i < s; i++) {
Future.delayed(Duration(seconds: i), () => print(i));
}
}
main() {
_printOrderMessage();
_countSeconds(5);
}
//打印结果
flutter: Awaiting user ordr ...
flutter: 0
flutter: 1
flutter: your order is : Large Latte
flutter: 2
flutter: 3
flutter: 4
main() async {
await _printOrderMessage();
_countSeconds(5);
}
flutter: Awaiting user ordr ...
//2s后
flutter: your order is : Large Latte
flutter: 0
flutter: 1
flutter: 2
flutter: 3
flutter: 4