Reputation: 117
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,
);
}
}
Upvotes: 10
Views: 14177
Reputation: 5926
Best solution found to avoid "Do not use BuildContexts across async gaps":
For a StateLess Widget :
if (context.mounted) {
Navigator.pop(context);
}
For a StateFull Widget:
if (mounted) {
Navigator.pop(context);
}
Upvotes: 7
Reputation: 1
if(context.mounted)
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: const ResetEmailScreen()
)
);
Upvotes: 0
Reputation: 661
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()));
Upvotes: 9
Reputation: 17732
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..
Upvotes: 19