During a FireAuth process, I need to store a user instance in my ChangeNotifier
appState.
Therefore I am meant to do that:
Provider.of<StateModel>(context, listen: false).signedIn = shokazeUser;
Unfortunately, I must fetch the shokazeUser
from the remote database via an await
modifier.
But doing so, I am exposed to the fact the context might no longer be valid.
I got the error:
Do not use BuildContexts across async gaps.
Because I am in a StatelessWidget
I can't do what would do in a StatefulWidget
aka testing mounted
.
What to do then?
My code's as follows:
Future<String?> _authUser(BuildContext context, LoginData data) {
debugPrint('Name: ${data.name}, Password: ${data.password}');
return auth
.signInWithEmailAndPassword(email: data.name, password: data.password)
.then((credential) async {
try {
final user = credential.user;
if (user == null) {
return 'Password does not match';
} else {
// == Tell the app we just signed in
try {
final shokazeUser = await shokaze.User.getFromId(user.uid);
if (shokazeUser == null) {
return "Unable to fetch user from database";
}
Provider.of<StateModel>(context, listen: false).signedIn =
shokazeUser;
} catch (e) {
return "Error while fetching user from database: $e";
}
return null;
}
} catch (e) {
return 'User not exists';
}
}).catchError((e) {
if (e.code == 'weak-password') {
debugPrint('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
debugPrint('The account already exists for that email.');
} else {
debugPrint(e.toString());
}
return Future<String?>.error(e);
});