5

我注意到我的项目中有一个新的 lint 问题。

长话短说:

我需要在我的自定义类中使用 BuildContext

与 aysnc 方法一起使用时,flutter lint 工具不满意。

例子:

   MyCustomClass{

      final buildContext context;
      const MyCustomClass({required this.context});

      myAsyncMethod() async {
        await someFuture();
        # if (!mounted) return;          << has no effect even if i pass state to constructor
        Navigator.of(context).pop(); #   << example
      }
   }
4

4 回答 4

7

不要将上下文直接存储到自定义类中,如果您不确定您的小部件是否已安装,请不要在异步之后使用上下文。

做这样的事情:

class MyCustomClass {
  const MyCustomClass();

  Future<void> myAsyncMethod(BuildContext context, VoidCallback onSuccess) async {
    await Future.delayed(const Duration(seconds: 2));
    onSuccess.call();
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: () => const MyCustomClass().myAsyncMethod(context, () {
        if (!mounted) return;
        Navigator.of(context).pop();
      }),
      icon: const Icon(Icons.bug_report),
    );
  }
}
于 2021-09-20T11:17:43.573 回答
0

进行此更改:

MyCustomClass{
  final buildContext context;
  const MyCustomClass({required this.context});

  myAsyncMethod() async {
    await someFuture();
    # if (!mounted) return;    
    Future.delayed(Duration.zero).then((_) {
      Navigator.of(context).pop();
    });
  }
}
于 2021-09-06T04:31:43.673 回答
0

只需将您的导航器或任何需要上下文的内容保存到函数开头的变量即可

      myAsyncMethod() async {
        final navigator = Navigator.of(context); // 1
        await someFuture();
        navigator.pop();  // 2
      }
于 2021-10-13T03:41:35.573 回答
0

不要跨异步间隙使用 BuildContext。

存储 BuildContext 以供以后使用很容易导致难以诊断崩溃。异步间隙隐式存储 BuildContext 并且是编写代码时最容易忽略的部分。

当从 StatefulWidget 使用 BuildContext 时,必须在异步间隙后检查 mount 属性。

所以,我认为,你可以这样使用:

好的:

class _MyWidgetState extends State<MyWidget> {
  ...

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

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

坏的:

void onButtonTapped(BuildContext context) async {
  await Future.delayed(const Duration(seconds: 1));
  Navigator.of(context).pop();
}
于 2022-02-15T08:38:07.133 回答