Pattern: Use of BuildContext
across asynchronous gaps
Issue: -
DO NOT use BuildContext across asynchronous gaps.
Storing BuildContext
for later usage can easily lead to difficult to diagnose
crashes. Asynchronous gaps are implicitly storing BuildContext
and are some of
the easiest to overlook when writing code.
When a BuildContext
is used from a StatefulWidget
, the mounted
property
must be checked after an asynchronous gap.
Example of correct code:
void onButtonTapped(BuildContext context) {
Navigator.of(context).pop();
}
Example of incorrect code:
void onButtonTapped(BuildContext context) async {
await Future.delayed(const Duration(seconds: 1));
Navigator.of(context).pop();
}
Example of correct code:
class _MyWidgetState extends State<MyWidget> {
...
void onButtonTapped() async {
await Future.delayed(const Duration(seconds: 1));
if (!mounted) return;
Navigator.of(context).pop();
}
}