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

lf3rwulv  于 2022-11-17  发布在  Flutter
关注(0)|答案(2)|浏览(268)
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)?

dohp0rv5

dohp0rv51#

查看Future.wait()上的文档。你可以同时运行多个future,最慢的一个确定它完成的总时间。它返回所有返回值的列表。

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也完成时出错,则放弃这些错误.

30byixjq

30byixjq2#

我不知道你想拖延什么,但我会根据我最好的理解来回答。
如果你想延迟上面的代码,那么你可以简单地使用Future。delayed like:

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;
                  }
             });

相关问题