简体   繁体   中英

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?. 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.

_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) . 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.

Therefore, When a BuildContext is used from a StatefulWidget, the mounted property must be checked after an asynchronous gap.

Solution

Use "if (!mounted) return;" before using context.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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