How to use Future Delayed

Viewed 5346

I have 2 functions. I want to run them one by one but while the first function is done, the second function must wait for 1-2 seconds. I tried Future.delayed for this but it did not work. It changes nothing.

void kartat(int tip, int deger, int mainid, List mycards) {
    masadakicards.add(cardbank[mainid]);
    print("kart atıldı");
    rakipkartat(51);

  }

  void rakipkartat(int mainid) {
    new Future.delayed(Duration(seconds: 1), () {
      // deleayed code here
      masadakicards.add(cardbank[mainid]);
      print("ann");
    });
  }
2 Answers

A way that you can achieve this is by using await Future.delayed

make sure that your method is returns a Future

Future<void> start() async {
  await foo();
  await Future.delayed(Duration(seconds: 2));
  await bar();
}

Future<void> foo() async {
  print('foo started');
  await Future.delayed(Duration(seconds: 1));
  print('foo executed');
  return;
}

Future<void> bar() async {
  print('bar started');
  await Future.delayed(Duration(seconds: 1));
  print('bar executed');
  return;
}

expected:

foo started
   - waits 1 second -
foo executed
    - waits 2 seconds -
bar started
    - waits 1 second -
bar executed

Following your methods

Please note that the method that gets executed after the delay also needs to include async and await, otherwise the method will run synchronously and not await the Future.

Future<void> start() async {
  foo();
}

void foo() {
  Future.delayed(Duration(seconds: 2), () async {
    // do something here
    await Future.delayed(Duration(seconds: 1));
    // do stuff
  });
}

Not sure if your overall approach is appropriate (can't tell from this), however, Future<void> rakipkartat(int mainid) async { should do.

I guess it would be better if you create both and the calling function as Future and then call the functions with await kartet(); await rakipkartat()

By the way, implementing my 1st paragraph also requests that the calling function is a Future or at least handles the call as a Future.

Related