SuperDeclarative
SuperDeclarative

Reputation: 1669

Flutter: How to handle screens that require authentication?

I'm building a Flutter app where some screens can be shown to anonymous users, and other screens require a user to be logged in.

For the authenticated screens, they should automatically navigate to (push) a login screen if the user is not logged in. A user session can expire at any time and if the user is viewing one of these authenticated screens then the login screen should be shown immediately at that time.

In Flutter, how can I achieve this notion of authenticated screens that automatically navigate to/from a login screen when the user is not authenticated?

Upvotes: 8

Views: 2538

Answers (2)

BartusZak
BartusZak

Reputation: 1253

There is a really good package auto_route for flutter.

It gives you a lot of power to implement Route Guards for Authenticated routes.

I'm encouring you to use the latest version of the library (on this time I'm writting the ansewer https://pub.dev/packages/auto_route/versions/1.0.0-beta.8 is the latest one)

The documentation is missleading but https://github.com/Milad-Akarie is actively working on that library and respond on any question under Issues tab on GitHub.

There is an example solution: https://github.com/Milad-Akarie/auto_route_library/tree/master/example

AppRouter.dart

...
AutoRoute(path: RoomPage.path, guards: [AuthGuard],page: RoomPage),
...

AuthGuard.dart

class AuthGuard extends AutoRouteGuard {
  @override
  Future<bool> canNavigate(
      List<PageRouteInfo> pendingRoutes, StackRouter router) async {
    bool isAuthenticated = await checkUserAccess();
    if (!isAuthenticated) {
      router.root.push(LoginRoute(onLoginResult: (success) {
        if (success) {
          router.replaceAll(pendingRoutes);
        }
      }));

      return false;
    }

    return true;
  }
}

Upvotes: 0

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277477

Currently, there's nothing that flutter do with Authentification and Authentified routes. The problem is that dart:mirror is disabled, which prevents from doing a more automated solution.

You could try to :

  • Put Anonymous routes in MaterialApp's routes property
  • Put Authentified routes in MaterialApp's onGenerateRoute property

And make sure inside onGenerateRoute that the user is logged. If he is, build that route. If not, build the Login route with the original destination passed as parameter (to later redirect to that page)

A code generator may be a good solution too ; although more complex.

Upvotes: 3

Related Questions