I would like to know the right way to use the onAuthStateChanges in Flutter web.
The flow of my should be the following:
if the user is logged in, then:
- if the page is the login page, it should redirect to the homepage;
- if the page is any other page but the login one, it should stay on that page;
If the user is NOT logged in, then:
- if the page is the login page, it should stay on that page;
- if the page is NOT the login page, it should redirect on the login page:
I have created my authentication service, and added a function as follows:
void listenToAuthChanges(Function onNotLoggedIn, Function onLoggedIn) {
FirebaseAuth.instance.authStateChanges().listen((firebaseUser) {
if (firebaseUser == null){
onNotLoggedIn();
}else{
onLoggedIn();
}
Then in the main() functions inside my main.dart file, I've added the following:
Future<void> main() async {
setupLocator();
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
var authService = locator<AuthenticationService>();
var navigationService = locator<NavigationService>();
authService.listenToAuthChanges(
() => {navigationService.pushNamedAndRemoveUntil(Routes.login)},
() => {navigationService.pushNamedAndRemoveUntil(Routes.homePage)});
runApp(MyApp());
}
This implementation works if I'm logged in and I land on the login page, but whatever page I'm on, it redirect me to the homepage (for the second function I've implemented).
My aim is to be redirected to the homepage only if I'm not logged in and I'm on the login page.
So I changed the implementation, deleting this function and adding it in initialize function of my login page (I'm using the package stacked with a Provider architecture), such that it is called only if I'm on the login page.
Following is my implementation:
Future<void> main() async {
setupLocator();
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
var authService = locator<AuthenticationService>();
var navigationService = locator<NavigationService>();
authService.listenToAuthChanges(
() => {navigationService.pushNamedAndRemoveUntil(Routes.login)},
() => {);
runApp(MyApp());
}
Inside my loginviewmodel.dart I've this function, that should be called only when the login page is called:
Future<void> initialise() async {
bool loggedIn = await authenticationService.isUserLoggedIn();
if (loggedIn) {
navigationService.pushNamedAndRemoveUntil(Routes.homePage);
}
}
The isUserLoggedIn() function is a utility function that return true if the auth.currentUser is not null, false otherwise.
The problem here is that this function, although it is inside the login page, it's called always, also if I redirect on other pages, so the behavior is the same as before.
My question are two:
- How do you handle onAuthStateChanges in Flutter Web?
- Does the route page (login page in my case) is called ALWAYS when I type the url of my web app, whatever page I call?
Thank you so much