use_build_context_synchronously
Do not use BuildContext
across asynchronous gaps.
此规则自 Dart 2.13 版本起可用。
_规则集:flutter _
详情
#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, a mounted
property must be checked after an asynchronous gap, depending on how the BuildContext
is accessed:
- When using a
State
'scontext
property, theState
'smounted
property must be checked. - For other
BuildContext
instances (like a local variable or function argument), theBuildContext
'smounted
property must be checked.
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(BuildContext context) async {
await Future.delayed(const Duration(seconds: 1));
if (!context.mounted) return;
Navigator.of(context).pop();
}
GOOD:
abstract class MyState extends State<MyWidget> {
void foo() async {
await Future.delayed(const Duration(seconds: 1));
if (!mounted) return; // Checks `this.mounted`, not `context.mounted`.
Navigator.of(context).pop();
}
}
使用方法
#要启用 use_build_context_synchronously
规则,请在你的 analysis_options.yaml
文件中,在 linter > rules 下添加 use_build_context_synchronously
:
linter:
rules:
- use_build_context_synchronously
除非另有说明,否则本网站上的文档反映的是 Dart 3.6.0。页面最后更新于 2025-02-05。 查看源代码 或 报告问题.