4
votes

I'm developing a web app using Flutter Web and Firebase.

I have to handle the Firebase Login.

Let's assume we have two screens, the situation that I want to achieve is the following:

if the user is not logged in:

  • Redirect the user on the login page

If the user is not logged in:

  • if he lands on the login page, redirect him on the homepage

I've implemented a functions that checks the current user in firebase and acts as following:

void checkAuthentication() {
var url = window.location.href;

var navigationService = locator<NavigationService>();

var loggedIn = this.isUserLoggedIn();
if (!loggedIn) {
  navigationService.replaceWith(Routes.login);
} else {
  if (url.contains("Login")) {
    navigationService.replaceWith(Routes.homepage);
  }
}

}

the navigationService is a service I took from the stacked package (https://pub.dev/packages/stacked).

This solution works, but has two problems:

  • this is not the right approach to do this. It's not possible that I have to call this in each screen page
  • When you are redirected you can see a transition with the new page presented.

My question: How would you manage this in Flutter Web in a unique point in the code? Is there a better way to achieve this differnt from the one I shown here?

1

1 Answers

0
votes

If you have the time checkout the first couple videos from The Net Ninja's Flutter/Firebase tutorial which go over basic authentication. I am pretty new to Flutter so I'll try my best to explain how he does it without going into detail:

He has a file wrapper.dart which uses a custom User object which constantly streams the authentication state. The wrapper decides where the user should navigate depending on authentication state.

 Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    print(user);

    // return either home or authenticate
    if (user == null) {
      return Authenticate();
    } else {
      return Home();
    }
  }

I am using this code in my project and it works well.