Skip to content

Files

Latest commit

 

History

History
50 lines (35 loc) · 1.12 KB

use_build_context_synchronously.md

File metadata and controls

50 lines (35 loc) · 1.12 KB

Pattern: Use of BuildContext across asynchronous gaps

Issue: -

Description

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();
 }
}

Further Reading