Home > Enterprise >  How to use Future.wait with flutter?
How to use Future.wait with flutter?

Time:11-01

Actually, I have many sublists and I have to display it one by one after recieving a signal (list contains[170,204]). that's why I have to use Future.wait. But this didn't work for me. what happens actually is that I send the first sublist then I resend the same sublist and after this there was no sublist sended. But when I tried to change the future.wait by Future.delayed it worked as expected. so the problem is on how I used the Future .wait this is my code :


  getValue() {
    _characteristic42?.value.listen(
        (notification) async => {print("Notification Value : $notification")});
  }
if (notification[0] == 170 && notification[1] == 204)
                  {
                    await Future.forEach(chun, (ch) async {
                      
                      await Future.delayed(const Duration(seconds: 4));
                      await c.write(ch, withoutResponse: true);
                      await c.read();
                      await Future.wait(getValue());
                    })

I would be very thankful if you can help me resolving this issue

CodePudding user response:

 await Future.wait([
  FirstFutureFunction(),
  secondFutureFunction(),
]);

CodePudding user response:

there are 2 approach to handle Future function. with await and with then. here an article i wrote to explain it: await vs then in Flutter

actually without Future.wait, your current code its already interupt the process before execute next function. because you are using await.

i think you missed this meaning: this => syntax means your function return 1 argument.in your code,it will return the print notification value.

solution:

getValue() {
  _characteristic42?.value.listen(
        (notification) async {
 print("Notification Value : $notification"));

if (notification[0] == 170 && notification[1] == 204)
{
  await c.write(yoursublist, withoutResponse: true);
  await c.read();
  });
 }
}

with the code above, its already execute line by line.

in that article i had explain the detail by example.

  • Related