1

When I press the login button, I receive a Future. If true, then I change page, else I display a popup dialog.

onPressed: () async {
  final navigator = Navigator.of(context); // store the Navigator to enable .push

  bool? res = await sendUser('6@gmail.com', 'password');
  // if connection succeeds
  if (res) {
     navigator.push(MaterialPageRoute(builder: (context) => const newScreen()));
  } else {
     showPopUp(context);
  }
}

I have the warning 'Do not use BuildContexts accros async gaps' for the popup. I had this warning for Navigator.push, so I fixed it by storing the Navigator but I don't know what to do for the popup. Can I get like the context of navigator ?

Jordaninho
  • 151
  • 1
  • 8

1 Answers1

1

Try surrounding your showPopUp function inside an if (mounted) like so:

onPressed: () async {
  final navigator = Navigator.of(context); // store the Navigator to enable .push

  bool? res = await sendUser('6@gmail.com', 'password');
  // if connection succeeds
  if (res) {
     navigator.push(MaterialPageRoute(builder: (context) => const newScreen()));
  } else if (mounted) { //Changed here <-------------
     showPopUp(context);
  }
}

PS: Caution when using ternary operators while this issue is open

FMorschel
  • 799
  • 5
  • 18
  • if (mounted) is used for stateful widget, I have stateless :/ – Jordaninho Jun 20 '22 at 14:36
  • I don't believe there is another way other than just ignoring the linter then. Changing your stateless widget to stateful is easy though, the Flutter extension gives a quick fix for that. – FMorschel Jun 20 '22 at 15:58