8

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,
      );
    }
  }
It'sPhil
  • 61
  • 1
  • 2
  • 11
  • lots of dupes https://stackoverflow.com/questions/72369932/flutter-do-not-use-buildcontexts-across-async-gaps – giorgio79 Sep 10 '22 at 12:05

3 Answers3

17

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

Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
9

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()));
Anmol Singh
  • 393
  • 3
  • 16
6

Best solution found to avoid "Do not use BuildContexts across async gaps":

if (context.mounted) {
   Navigator.pop(context);
}
Alain Beauvois
  • 5,896
  • 3
  • 44
  • 26