Home > Net >  Flutter - How to delay a task at least 2 seconds but not longer than necessary?
Flutter - How to delay a task at least 2 seconds but not longer than necessary?

Time:11-15

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

This code took 2.373 seconds to complete. How to delay for 2 seconds and do another small task (0.373 seconds) at the same time (so the total delay is 2)?

CodePudding user response:

Check out the documentation on Future.wait(). You can run multiple futures at the same time, the slowest one determining the total time until it completes. It returns a list of all return values.

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];

Please note: "If any future completes with an error, then the returned future completes with that error. If further futures also complete with errors, those errors are discarded."

CodePudding user response:

I am not sure what are you trying to delay but I'll answer it according to my best understanding.

If you want to delay the code above then you can simply use Future.delayed like:

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

which will translate to :

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