1、在 Flutter 中,使用 then 方法对 Future 对象进行操作后,返回的仍然是一个 Future 对象。但是,这个新的 Future 对象的值,取决于你传入 then 方法的回调函数的行为。
Future 对象代表一个异步操作的结果。当 Future 对象完成时,它会包含一个值。then 方法允许你注册一个回调函数,当 Future 完成时,这个回调函数会被调用。
回调函数接受 Future 对象的值作为参数,并返回一个新的值。这个新的值可以是原始 Future 对象的值,也可以是新的值。
- 新 Future 对象的值是由 then 方法的回调函数决定的。
- 如果回调函数返回值是原始 Future 的值,则新的 Future 对象会包含原始 Future 的值。
- 如果回调函数返回新的值,则新的 Future 对象会包含回调函数返回的值。
如果then方法不返回值,则新的 Future 对象 value值为null
2、如果 then 里面又是一个延时操作,这个新的 Future 是需要等待 then 里面延时操作执行完成的。
- then 方法的作用是:当原始 Future 完成时,执行 then 中的回调函数。
- 如果 then 中的回调函数本身是一个异步操作,例如延时操作,那么新的 Future 必须等待这个异步操作完成,才能最终完成。
- 只有当新的 Future 完成时,你才能获取到它的值。
下面是相关测试代码:
import 'dart:async';
Future<String> getGreeting() async {
await Future.delayed(const Duration(seconds: 1));
return 'Hello!';
}
void test1() async {
Future<String> originalFuture = getGreeting();
Future<String?> newFuture = originalFuture.then((value) {
// 回调函数没有 return 语句
print(value); // 输出:Hello!
});
print(await newFuture); // 输出:null
}
void test2() async {
Future<String> originalFuture = getGreeting();
Future<String> newFuture = originalFuture.then((value) async {
print(value); // 输出:Hello!
await Future.delayed(const Duration(seconds: 2)); // 延时操作
return '$value World!';
});
print(await newFuture); // 3 秒后输出:Hello! World!
}
网友评论