use_ build_ context_ synchronously
Details about the 'use_build_context_synchronously' diagnostic produced by the Dart analyzer.
Don't use 'BuildContext's across async gaps, guarded by an unrelated 'mounted' check.
Don't use 'BuildContext's across async gaps.
Description
#
The analyzer produces this diagnostic when a
BuildContext is referenced by a
StatefulWidget after an asynchronous gap without
first checking the mounted property.
Storing a BuildContext for later use can lead to
difficult-to-diagnose crashes. Asynchronous gaps implicitly
store a BuildContext, making them easy to
overlook for diagnosis.
Example
#
The following code produces this diagnostic because the
context is passed to a constructor after the
await:
import 'package:flutter/material.dart';
class const MyWidget({super.key}) extends Widget {
void onButtonTapped(BuildContext context) async {
await Future.delayed(const Duration(seconds: 1));
Navigator.of(context).pop();
}
}
Common fixes
#If you can remove the asynchronous gap, do so:
import 'package:flutter/material.dart';
class const MyWidget({super.key}) extends Widget {
void onButtonTapped(BuildContext context) {
Navigator.of(context).pop();
}
}
If you can't remove the asynchronous gap, then use
mounted to guard the use of the
context:
import 'package:flutter/material.dart';
class const MyWidget({super.key}) extends Widget {
void onButtonTapped(BuildContext context) async {
await Future.delayed(const Duration(seconds: 1));
if (context.mounted) {
Navigator.of(context).pop();
}
}
}
除非另有说明,文档之所提及适用于 Dart 3.12.2 版本报告页面问题.