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.
CodePudding user response:
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.