Consider this first example:
Future<void> initializeServices() async {
await notificationService.begin();
await geotrackingService.begin();
Navigator.of(context).pop(); // Don't use 'BuildContext's across async gaps.
}
Now, consider this second example:
Future<void> initializeServices() async {
await notificationService.begin();
await geotrackingService.begin();
exitScreen();
// exitScreenAsync();
}
void exitScreen() {
Navigator.of(context).pop(); // The compiler is satisfied now.
}
Future<void> exitScreenAsync() async {
Navigator.of(context).pop(); // The compiler remains satisfied?
}
As you can see, the only difference between these two examples is that the the second example is popping the navigator by calling a function while the first one is not. However, with the second exmaple the compiler is perfectly fine and no warning is displayed.
I find this warning a bit stupid and meaningless. Why do I have to move the code section that makes use of the BuildContext
across async gaps to a proxy function just to get rid of this warning?
No it's not useless warning. The problem is that after an await, every use of the BuildContext will show this warning. This warning happens because using a BuildContext after an await could happen after the widget is disposed of. This way, the context wouldn't exist anymore and the app could even crash because of this. Check out the official lint documentation:
if (context.mounted) Navigator.of(context).pop();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With