Rafael Reis
Rafael Reis

Reputation: 29

Dart: Logic for/if

I have a logic problem, this is my code:

  bool teste = true;

  for (int j = 0; j < items.length; j++) {
    verifyAllProd(items[j].ref).then(
      (quanti) {
        if (double.parse(quanti) <= 0) {
          teste = false;
          _dialogBuilder(context, items[j].name);
        }
        if (double.parse(quanti) <
                items[j].quantity &&
            double.parse(quanti) != 0) {
          teste = false;
          _dialogBuilder2(
              context, items[j].name, quanti);
        }
      },
    );
  }

  if (teste) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) =>
            const ListPaymentTrans(),
      ),
    );
  }

That I wanted the last "if" to happen when: The "for" was running but it didn't enter any "if", if they enter one then it shows the message and no longer opens another window, ie the last if.

But this is not happening, when I run the code it starts to go through the "for" and at the same time opens the "if", can anyone help?

Upvotes: 0

Views: 72

Answers (1)

Tuan
Tuan

Reputation: 2433

Look like you have an async function verifyAllProd here. The code inside then will run async, so the last "if" will run first of all.

Eg: "end" will go first, then all the "verify" will go after.

Future<String> verify(String text) async {
  await Future.delayed(Duration(milliseconds: 200));
  return 'verified_$text';
}

void main() {
  const count = 5;
  for(int i = 0; i < count;i++){
    verify('count$i').then((verifiedText) {
      print(verifiedText);
    });
  }
  print('end.');
}
// end.
// verified_count0
// verified_count1
// verified_count2
// verified_count3
// verified_count4

enter image description here

You may want to wait all the async function done first, try to use async/await like this

enter image description here

Upvotes: 1

Related Questions