Flutter App Middleware

Middleware plays an important role before your app send response back to server or even within the app itself. We can use middleware to redirect user to a different page or screen based on condition. 

Simply speaking in middleware, you will put your condition and flutter routing system will check the condition before, user is redirected to anywhere else.

I will make a very simple example of middleware use case. The very first one would be showing your onbaording or splashscreen only once. 

As you next time launch the app or reboot, you don't wanna show the onboarding page or splashscreen. We may acheive this using middleware.

Flutter Getx provides a convenient way to acheive this. All you need to do, create a new dart class and put anywhere you want. 

import 'package:get/get.dart';

/// onboarding page or welcome page middleware
class RouteWelcomeMiddleware extends GetMiddleware {
  // priority this value the smaller the better
  @override
  int? priority = 0;

  RouteWelcomeMiddleware({required this.priority});

  @override
  RouteSettings? redirect(String? route) {
    print(ConfigStore.to.isFirstOpen);
    if (ConfigStore.to.isFirstOpen == false) {
      return null;
    } else if (UserStore.to.isLogin == true) {
      return RouteSettings(name: AppRoutes.Application);
    } else {
      return RouteSettings(name: AppRoutes.SIGN_IN);
    }
  }
}

We created a class name RouteWelcomeMiddleware, and this class extends GetMiddleware. We will need to override two things

  1. priority variable
  2. redirect function

priority is any value, the lower the better. redirect function is the core part of this middleware, Inside of this function, we can put our conditional check and redirect user to a different page.

We call this class, from our routes GetPage(). 

  static final List<GetPage> routes = [
    
    GetPage(
      name: AppRoutes.INITIAL,
      page: () => WelcomePage(),
      binding: WelcomeBinding(),
      middlewares: [
        RouteWelcomeMiddleware(priority: 1),
      ],
    ),
]

From GetPage() middlwares we are calling RouteWelcomeMiddleware().

The above middleware would check if the user has logged in our. If the user has logged in it won't show the Welcome() page anymore.

Before we go to dashboard or personal center or chatting screens, we may also do check using middleware. If the user has already logged in, then user may go to dashboard, personal center or chatting pages.

/// 检查是否登录
class RouteAuthMiddleware extends GetMiddleware {
  // priority 数字小优先级高
  @override
  int? priority = 0;

  RouteAuthMiddleware({required this.priority});

  @override
  RouteSettings? redirect(String? route) {
    if (UserStore.to.isLogin || route == AppRoutes.SIGN_IN || route == AppRoutes.INITIAL) {
      return null;
    } else {
      Future.delayed(
          Duration(seconds: 1), () => Get.snackbar("Warning", "You must login"));
      return RouteSettings(name: AppRoutes.SIGN_IN);
    }
  }
}

We created a class name RouteAuthMiddleware and it checks if the user is logged in or not.You may also do many other conditional check in the redirect method().

  static final List<GetPage> routes = [
    // 免登陆
    GetPage(
      name: AppRoutes.INITIAL,
      page: () => WelcomePage(),
      binding: WelcomeBinding(),
      middlewares: [
        RouteWelcomeMiddleware(priority: 1),
      ],
    ),
    GetPage(
      name: AppRoutes.SIGN_IN,
      page: () => SignInPage(),
      binding: SignInBinding(),
    ),

    // check if needed to login or not
    GetPage(
      name: AppRoutes.Application,
      page: () => ApplicationPage(),
      binding: ApplicationBinding(),
      middlewares: [
        RouteAuthMiddleware(priority: 1),
      ],
    ),

];

Recent posts