I'm using Firebase with Flutter to create a login method. However, when I log out of my account in the Flutter app, I get the following error:
This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
Then when I log in after this error, I get this error:
setState() or markNeedsBuild() called during build.
Here is my logout code:
Future<void> signOut() async {
if (googleSignIn.currentUser != null){
await googleSignIn.disconnect();
await FirebaseAuth.instance.signOut();}
else{
await FirebaseAuth.instance.signOut();
}
WidgetsBinding.instance.addPostFrameCallback((_) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) => const AuthPage(),
),
(route) => false,
);
});
}
And here is the sign in code:
Future googleLogin() async{
timer1 = Timer(const Duration(milliseconds: 1500), (){
Navigator.of(context, rootNavigator: true).pop();
});
showDialog(context: context,
barrierDismissible: false,
builder: (context) => Center(
child: SizedBox(
width: 150, height: 150,
child: LiquidCircularProgressIndicator(
backgroundColor: const Color(0xFF5B84B1),
valueColor: const AlwaysStoppedAnimation(Colors.white),
),
),
),
).then((value) {
timer1!.cancel();
});
try {
final googleUser =
await GoogleSignIn(scopes: ['profile', 'email']).signIn();
if (googleUser == null) return;
_user = googleUser;
final googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
UserCredential userCredential = await _auth.signInWithCredential(
credential);
if (userCredential.additionalUserInfo!.isNewUser == true) {
if (!mounted) return;
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) => const ProfilePage(),
),
(route) => false,
);
}
else {
if (!mounted) return;
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) => const HomeScreen(),
),
(route) => false,
);
}
} on PlatformException catch (e) {
Utils.showSnackBar(e.toString());
}
}
You can check if it is mounted or not, then proceed:
if (mounted) {
// All the action is here
}