简体   繁体   English

不要跨异步间隙使用 BuildContexts。 将 pub yaml 更新到主要版本后

[英]Do not use BuildContexts across async gaps. After update pub yaml to the major version

I have upgraded the pub yaml to the major version flutter pub upgrade --major versions and it gave me a lot of suggestions error I don't understand why?.我已将 pub yaml 升级到主要版本flutter pub upgrade --major versions ,它给了我很多建议错误,我不明白为什么? Can someone explain?有人可以解释吗?

And this is for an example.这是一个例子。 It says Do not use BuildContexts across async gaps What am I suppose to do here.它说Do not use BuildContexts across async gaps我想在这里做什么。

_resetEmail(String password,) async {
    final user = FirebaseAuth.instance.currentUser;
    final credential =
        EmailAuthProvider.credential(email: user!.email!, password: password);
    try {
      UserCredential;
      await FirebaseAuth.instance.currentUser
          ?.reauthenticateWithCredential(credential);

       ///The problem is here
      Navigator.push(
          context,
          PageTransition(
              type: PageTransitionType.rightToLeft,
              child: const ResetEmailScreen()));
        ///

    } on FirebaseAuthException {
      Fluttertoast.showToast(
        msg: 'Wrong password',
        gravity: ToastGravity.TOP,
        toastLength: Toast.LENGTH_LONG,
        backgroundColor: Colors.grey[400],
        textColor: Colors.black,
      );
    }
  }

Before Navigator.push add a condition if (mounted) .在 Navigator.push 之前添加条件if (mounted) You are using a context in an async method.您正在异步方法中使用上下文。 While this method is being executed the context can change.在执行此方法时,上下文可能会发生变化。 But this context is being passed to the navigator.但是这个上下文被传递给导航器。 Hence the error i think..因此我认为错误..

Storing BuildContext in a method is causing Asynchronous gaps which can later cause difficulty in finding the problem if the app crashes.将 BuildContext 存储在方法中会导致异步间隙,如果应用程序崩溃,以后可能会难以找到问题。

Therefore, When a BuildContext is used from a StatefulWidget, the mounted property must be checked after an asynchronous gap.因此,当从 StatefulWidget 使用 BuildContext 时,必须在异步间隙后检查 mount 属性。

Solution解决方案

Use "if (!mounted) return;"使用“if (!mounted) return;” before using context.在使用上下文之前。

if (!mounted) return;
  Navigator.push(
      context,
      PageTransition(
          type: PageTransitionType.rightToLeft,
          child: const ResetEmailScreen()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM