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)?
2条答案
按热度按时间dohp0rv51#
查看Future.wait()上的文档。你可以同时运行多个future,最慢的一个确定它完成的总时间。它返回所有返回值的列表。
请注意:如果任何future完成时出错,则返回得future完成时出错.如果进一步得future也完成时出错,则放弃这些错误.
30byixjq2#
我不知道你想拖延什么,但我会根据我最好的理解来回答。
如果你想延迟上面的代码,那么你可以简单地使用Future。delayed like:
这将转化为: