I am using provider for the state management on Flutter. I'm making async await function and have warning that Do not use BuildContexts across async gaps. So I tried to put 'if(!mounted)' code and I got warning that Undefined name 'mounted'.
How can I fix this problem? Thank you!
Provider codes
signIn(BuildContext context) async{
try {
final navigator = Navigator.of(context);
!isSignupValid ? isSignupValid = true : null;
await authentication.signInWithEmailAndPassword(
email: userEmail.trim(), password: userPassword.trim()
);
navigator.pop();
} on FirebaseAuthException catch (errorCode) {
isSignupValid = false;
print('isSignupValid : $isSignupValid');
print('SignIn FirebaseAuthException : $errorCode');
ScaffoldMessenger.of(context).showSnackBar(
returnSnackBar(context, errorCode)
);
}
await Future.delayed(const Duration(seconds: 0));
if (!mounted) return;
context.watch<ProfileData>().profileImage = null;
notifyListeners();
}
CodePudding user response:
The mounted
property is only available in a StatefulWidget
. If you are not in a stateful widget you have no way of knowing whether the context you are using still references the state of a widget which is still in the widget tree.
I'm not sure exactly what you do. You can either change your widget to a StatefulWidget
or simply do a final profileData = context.read<ProfileData>()
at the beginning of you method, and never access context
after your first async
call.