This is an introductory tutorial, more suitable for small projects.

I. Why is route interception needed

If we want to automatically redirect to the login page when the user is not logged in, we can view other pages while logged in. It is very troublesome to judge the login status every time the page is opened. We can use the onGenerateRoute property of the MaterialApp.

2. OnGenerateRoute introduction

  • onGenerateRouteThis parameter is valid only for named routes
  • onGenerateRouteProperty, which may be called when a named route is turned on
  • If the specified route name is registered in the routing table, the routing table is invokedbuilderFunction to generate a routing component
  • This parameter is invoked only if the routing table is not registeredonGenerateRouteTo generate routes

3. Preparation

According to onGenerateRoute above, we must do the following:

MaterialApp(
    // home: MyHomePage(),
    // routes: routes,
    initialRoute: "index",
    onGenerateRoute: onGenerateRoute,
);
Copy the code
  • Example Delete routing table routes
  • Delete the home
  • Using initialRoute

Create onGenerateRoute function

Route<dynamic> onGenerateRoute(RouteSettings settings) { String routeName; routeName = routeBeforeHook(settings); Return MaterialPageRoute(Builder: (context) {/// Note: if the route form is: '/ a/b/c / / / will, in turn, retrieval'/' - > '/ a' - > '/ a/b' - > '/ a/b/c / / / so, named after the routing here I avoid using'/XXX 'form switch (routeName) {case "index" : return MyHomePage(); case "login": return LoginScreen(); Default: return Scaffold(body: Center(child: Text(" page does not exist "),),); }}); }Copy the code

To this point we only implement the route name -> specific page mapping, the next to implement the “route hook”, used to achieve interception function.

Five. Achieve the interception function

Create the routeBeforeHook function and call it in the onGenerateRoute function

String routeBeforeHook(RouteSettings Settings) {/// Global.prefs is a Global SharedPreferences instance Final Token = global.prefs.getString ('token')?? "'; if (token ! = '') { if (settings.name == 'login') { return 'index'; } return settings.name; } return 'login'; }Copy the code

6. The final

Don’t be stingy with your hands of praise ah!

End.