My Flutter app contains few screens like settings,add product,Details page.
I am using FirebaseAuth.instance.onAuthStateChanged in stream builder in Main Page to decide to show Login or HomePage based on the onAuthStateChanged change, if the user is in setting page and clicks on logout which is "FirebaseAuth.instance.signOut();" , app stays on the same setting page and does not redirects to login page as mentioned in stream builder which we use in Main page as below.
MaterialApp(
home: StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (ctx, snapSot) {
if (snapSot.hasData) {
return HomePage();
} else
return LoginScreen();
},
),),)
Package version:
- provider: ^4.1.2
- firebase_auth: ^0.16.1
My expectation:
In which ever page the user is , if he logs out he has to be taken to the login screen. As i am using Streambuilder and i have provided the stream source as onAuthStateChanged.
Working Scenario:
But when the user clicks the logout when he is in Homepage screen its working as expected and the user is taken to the login page.
Not Working Scenario:
IF the user is in any other page its not redirecting to login page.I can see the below logs in console when sign out is clicked.
Scenario : User Navigation : Login ->HomePage -> App Drawer -> Settings Page ->Logout
I/flutter ( 6186): HomePage
I/flutter ( 6186): appDrawer
I/flutter ( 6186): Settings
I/flutter ( 6186): appDrawer
I/flutter ( 6186): logoutDialog
D/FirebaseAuth( 6186): Notifying id token listeners about a sign-out event.
D/FirebaseAuth( 6186): Notifying auth state listeners about a sign-out event.
Work Around tried using Stream:
Main App file:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamProvider<UserAccount>.value(
value: Authservice().user,
child: MaterialApp(
home: Wrapper(),
onGenerateRoute: CustomRouter.generateRoute,
initialRoute: homeRoute,
),
);
}
}
class Wrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
final user = Provider.of<UserAccount>(context);
print("user: $user");
if (user == null)
return LoginScreen();
else
return Dashboard();
}
}
Authservice File :
Stream<UserAccount> get user {
return _auth.onAuthStateChanged.map(_userFBAccount);
}
UserAccount _userFBAccount(FirebaseUser user) {
return user != null
? UserAccount(
uid: user.uid,
)
: null;
}
Future<void> logout() async {
try {
print("logout");
await _auth.signOut();
} catch (error) {
print("logout $error");
}
}
Alert Dialogue button code
FlatButton(
onPressed: () async {
Navigator.of(ctx).pop(); // to pop put the alert Dialogue
await _authservice.logout().then((value) {
if (Navigator.canPop(ctx)) Navigator.of(ctx).pop();
});
},
child: const Text("Yes"),
shape: Border(
right: BorderSide(color: Colors.grey),
),
),
Am i missing out some logic here or is this an issue with the Firebase_auth plugin onAuthStateChanged ?
Thanks