Future 是在未来某个时间获得想要对象的一种手段.
1、定义一个名为ff的future,返回字符串。
Future<String> ff = Future(() {
return 'future test';
});
ff.then((value) => print(value));
网络请求示例
Future<Map<String,dynamic>> getShopListData() async{
var data = //耗时的操作
return data;
}
2、future其他用法
//1
Future.delayed(Duration(seconds: 2), () {
print('test future1');
});
//2
var future = Future.delayed(Duration(seconds: 2), () {
return 'test future2';
});
future.then((value) => print(value));
//3
Future<String> testFuture() async {
var futureResult = await Future.delayed(Duration(seconds: 2), () {
return 'test future3';
});
return futureResult;
}
testFuture().then((value) => print(value)).catchError((e) {});
//4
Future<String> getUserName(String parameter) {
return Future.value(parameter);
}
getUserName('jacky').then((value) => print('my name is' + value));
//4
Future<Map<String, dynamic>> getUserInfo(String parameter) async {
final map = await {'name': 'jacky'};
return map;
}
getUserInfo('jacky').then((value) => print('userinfo is' + value.toString()));
//5
Future<Map<String, dynamic>> getUserInfo2(
String parameter, Function(String name, String email) userFunc) async {
final map = await {'name': 'jacky'};
userFunc('Jacky', '123456@qq.com');
return map;
}
getUserInfo2(
'Jacky',
(name, email) => {
print('user name and email is' + name + '??' + email)
}).then((value) => print(value));
//6
Future.wait([
Future.delayed(Duration(seconds: 2), () {
return 'hello1';
}),
Future.delayed(Duration(seconds: 3), () {
return 'hello2';
}),
Future.delayed(Duration(seconds: 4), () {
return 'hello3';
}),
]).then((value) => print(value));