my goal in flutter is to ensure that the app closes after the user has logged out. However, I have a small problem here.
in my application the user is asked if he wants to log out if he presses yes the following code is executed.
onPressed: () async {
var auth = FirebaseAuth.instance;
await auth.signOut();
FirebaseAuth.instance.authStateChanges().listen((User? user) {
if (user == null) {
print('Exiting app');
exit(8); //this closes the app
}
});
},
However, this causes me to get a message in the console that the user is logged out and then the app closes as expected. However, if I then open the app, the user is logged in again. How can I prevent this?
my Console output (after pressing the Button) is as follows:
D/FirebaseAuth( 2809): Notifying id token listeners about a sign-out event.
D/FirebaseAuth( 2809): Notifying auth state listeners about a sign-out event.
I/flutter ( 2809): Exiting app
The issue you're facing occurs because exit()
forcibly closes the app without properly saving the user's logged-out state. This could prevent Firebase from fully processing the logout event.
Instead, use SystemNavigator.pop()
, and also make sure that you clear any stored session if you have used it:
onPressed: () async {
var auth = FirebaseAuth.instance;
await auth.signOut(); // Signs out the user
// Clear any local storage or session data
// For example, using shared preferences:
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.clear(); // Clear stored user session
FirebaseAuth.instance.authStateChanges().listen((User? user) {
if (user == null) {
print('User logged out successfully');
SystemNavigator.pop(); // Close the app gracefully
}
});
},