颤振-如何延迟任务至少2秒,但不超过必要的时间?


DateTime beforeDate = DateTime.now();
await Future.delayed(Duration(seconds: 2));
try {
return await FirebaseFirestore.instance
.collection('news')
.where('id', isEqualTo: id)
.get()
.then((snapshot) {
DateTime afterDate = DateTime.now();
print(afterDate.difference(beforeDate).inMilliseconds);//2.373 seconds
return NewsModel.fromJson(snapshot.docs.first.data());
});
} catch (ex) {
print('ex: $ex');
rethrow;
}

这段代码花了2.373秒才完成。如何延迟2秒,同时做另一个小任务(0.373秒)(所以总延迟是2)?

查看有关Future.wait()的文档。您可以同时运行多个期货,最慢的一个决定总时间,直到它完成。它返回所有返回值的列表。

final returnValues = await Future.wait<void>([
Future.delayed(const Duration(seconds: 2)),
FirebaseFirestore.instance
.collection('news')
.where('id', isEqualTo: id)
.get(),
]);
final mySnapshots = returnValues[1];

请注意: "如果任何future以错误结束,则返回的future以该错误结束。如果以后的期货也有错误,这些错误将被丢弃。">

我不知道你想拖延什么,但我会根据我最好的理解来回答。

如果你想延迟上面的代码,那么你可以简单地使用Future.delayed:

Future.delayed(Duration(seconds: 2), (){
// Your code over here
});

转换成:

Future.delayed(Duration(seconds: 2), (){
try {
return await FirebaseFirestore.instance
.collection('news')
.where('id', isEqualTo: id)
.get()
.then((snapshot) {
DateTime afterDate = DateTime.now();
print(afterDate.difference(beforeDate).inMilliseconds);//2.373 seconds
return NewsModel.fromJson(snapshot.docs.first.data());
});
} catch (ex) {
print('ex: $ex');
rethrow;
}
});

最新更新