Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Future Delayed

Tags:

flutter

dart

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");
    });
  }
like image 264
Emre Varol Avatar asked Apr 26 '26 04:04

Emre Varol


1 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
  });
}
like image 134
mrgnhnt96 Avatar answered Apr 27 '26 17:04

mrgnhnt96



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!