use_build_context_synchronously

Group: errors

Maturity: experimental

Dart SDK: >= 2.13.0 • (Linter v1.1.0)

Since info is static, may be stale
flutter

View all Lint Rules

Using the Linter

DON'T 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, its mounted property must be checked after an asynchronous gap.

BAD:

void onButtonTapped(BuildContext context) async {
  await Future.delayed(const Duration(seconds: 1));
  Navigator.of(context).pop();
}

GOOD:

void onButtonTapped(BuildContext context) {
  Navigator.of(context).pop();
}

GOOD:

void onButtonTapped() async {
  await Future.delayed(const Duration(seconds: 1));

  if (!context.mounted) return;
  Navigator.of(context).pop();
}

Usage

To enable the use_build_context_synchronously lint, add use_build_context_synchronously under linter > rules in your analysis_options.yaml file:

linter:
  rules:
    - use_build_context_synchronously