0

I am trying to build a signOut feature on an ElevatedButton(). In the onPressed() method, I write an async function to signOut and navigate back to the first Screen of the App.

After writing this, I encountered a warning to not put BuildContexts in async gaps. I don't have a clue, what this means and what should be the better approach for this.

Here is the code snippet:

ElevatedButton(
                    onPressed: () async {
                      await AuthService().signOut();
                      Navigator.of(context)
                          .pushNamedAndRemoveUntil('/', (route) => false);
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.yellow,
                    ),
                    child: const Text('Sign Out'),
                  ),

Any approach to this query would be very helpful. Thank you.

Marian Klösler
  • 620
  • 8
  • 22
Anurag Hale
  • 133
  • 9

1 Answers1

1

After the async call, you need to check if the widget is still mounted before you use a BuildContext. The reason for this that during the async call the widget could be removed from the tree and therefore the context which Navigator.of uses can be invalid:

onPressed: () async {
  await AuthService().signOut();
  if (mounted) {
    Navigator.of(context)
        .pushNamedAndRemoveUntil('/', (route) => false);
  }
}

This should remove the warning.

Peter Koltai
  • 8,296
  • 2
  • 10
  • 20
  • Quick follow-up question: would this work if you got navigator object before calling async method: ````var navigator=Navigator.of(context); await ...; navigator.pushNamedAndRemoveUntil...````. Assuming here that if yuour widget is not mounted anymore - but the Navigator above it is. – Andrija Jan 23 '23 at 12:46
  • It could throw a runtime error, because the `context` variable you use to get the `Navigator` may be now longer valid after the `async` call is completed. You can get a global key for `Navigator` to overcome this, check the accepted answer [here](https://stackoverflow.com/questions/52962112/how-to-navigate-without-context-in-flutter-app) for example. – Peter Koltai Jan 23 '23 at 12:59