Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the warning "Don't use 'BuildContext's across async gaps" a useless warning?

Tags:

flutter

dart

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?

like image 999
XUNIT Avatar asked Sep 01 '25 10:09

XUNIT


1 Answers

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();
like image 78
Rohan Jariwala Avatar answered Sep 04 '25 14:09

Rohan Jariwala