DEV Community

Cover image for Resolve your routes
Cristovão Farias
Cristovão Farias

Posted on

Resolve your routes

There are times when we want to work with a login feature and need to create different routes based on the user's status, redirecting them to the registration page or even identifying a user with a bonus. In these cases, we often place the code directly on the page and send the user to the appropriate route based on their state or status.

class AuthState {
  final bool isAuthenticated;

  AuthState(this.isAuthenticated);
}

void main() {
  final authState = AuthState(isAuthenticated: false);

  String initialRoute;
  if (authState.isAuthenticated) {
    initialRoute = '/home';
  } else {
    initialRoute = '/login';
  }

  runApp(MyApp(initialRoute: initialRoute));
}

Enter fullscreen mode Exit fullscreen mode

However, this is not always the best solution because, depending on the number of routes, the logic in the view can become extensive and unwieldy if there is no standard or pattern in place. With this in mind, we can consider a solution to the problem, something that allows for unit testing if necessary.

We will create a simple abstraction using generic types, where we will have a method that returns the route string. The method's return can be an enum of routes or something similar, as long as we have control over it.

abstract class RouteResolver<T> {
  String resolveRoute(T states);
}
Enter fullscreen mode Exit fullscreen mode

With our abstraction created, let's now implement our Resolver by module. This way, we separate the logic from the view, allowing us to inject our resolver as a dependency or, for simpler cases, instantiate it on the page where we need to use it.

class AuthState {
  bool isAuthenticated;

  AuthState(this.isAuthenticated);
}

class AuthRouteResolver implements RouteResolver<AuthState> {
  @override
  String resolveRoute(AuthState states) {
    if (states.isAuthenticated) {
      return '/home';
    } else {
      return '/login';
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Instantiating our route resolver.

void main() {
  final authState = AuthState(isAuthenticated: true);

  final routeResolver = AuthRouteResolver();
  final initialRoute = routeResolver.resolveRoute(authState);

  runApp(MyApp(initialRoute: initialRoute));
}
Enter fullscreen mode Exit fullscreen mode

I believe this is a simple solution to a common problem. Of course, there are other ways to work with routes. In this particular case, we are working based on a state, status, or even a class type, hence the importance of using generic types. To better understand the topic discussed here, I recommend reading about clean architecture, clean code, and code refactoring.

Top comments (0)