我一直在开发 Flutter 应用程序,上周我更新了 flutter_lints 并注意到我的项目中出现了一个新的 lint 问题:
看了很多答案我还是不明白哪个是正确的
选项 1:
void foo(BuildContext context) async {
await someFuture();
if (!context.mounted) return;
Navigator.pop(context); // No warnings now
}
选项2:
MyCustomClass{
const MyCustomClass({ required this.context });
final buildContext context;
myAsyncMethod() async {
// Declare navigator instance (or other context using methods/classes)
// before async method is called to use it later in code
final navigator = Navigator.of(context);
await someFuture();
// Now use the navigator without the warning
navigator.pop();
}
}
选项 3:
Future<void> myAsyncMethod(BuildContext context) async {
await Future.delayed(const Duration(seconds: 3));
if (context.mounted) {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => const MainScreen()));
}
}
感谢任何帮助,谢谢uuuu
选项 1 是最好的,因为即使在异步操作期间,您也可以简单地跟踪小部件子树与其各自的 BuildContext 保持正确关联。 这是一条线解决方案。
选项 2 很好,但它比选项 1 长,因为你需要声明它,然后你必须使用它。 此外,跟踪子树是否与 BuildContext 关联也很复杂。
选项 3 或多或少与选项 1 相同,但为了更清晰的代码方法,选项 1 更好。