The small dish plan is to make a summary of the knowledge related to the routing between page jumps. I find that there are two special methods that have not been studied yet. Today, I will add the application of Navigator related methods.

canPop

Navigator is the operation of the stack. For the process of pushing out the stack, canPop can be used to determine whether the Page in the stack exists, so as to prevent exceptions caused by forced Pop out of the stack when there is no element in the stack.

The source code parsing

bool canPop() {
    return _history.length > 1 || _history[0].willHandlePopInternally;
}
Copy the code

Case try

If (navigator.of (context).canpop ()) {print(' current ${modalroute.of (context).settings.name} canPop! '); Navigator.pop(context); } else {print(' Current Page cannot Pop! ModalRoute.of(context).isFirst = ${ModalRoute.of(context).isFirst}'); }Copy the code

maybePop

CanPop is only a judgment on whether elements in the stack can be pushed out, while maybePop can not only judge but also perform the Pop operation.

The source code parsing

Future<bool> maybePop<T extends Object>([ T result ]) async { final _RouteEntry lastEntry = _history.lastWhere(_RouteEntry.isPresentPredicate, orElse: () => null); if (lastEntry == null) return false; final RoutePopDisposition disposition = await lastEntry.route.willPop(); // this is asynchronous if (! mounted) return true; // forget about this pop, we were disposed in the meantime final _RouteEntry newLastEntry = _history.lastWhere(_RouteEntry.isPresentPredicate, orElse: () => null); if (lastEntry ! = newLastEntry) return true; // forget about this pop, something happened to our history in the meantime switch (disposition) { case RoutePopDisposition.bubble: return false; case RoutePopDisposition.pop: pop(result); return true; case RoutePopDisposition.doNotPop: return true; } return null; }Copy the code

Simple analysis of the source code can be obtained, maybePop will be limited to determine whether the current routing stack is the last in the list, if it is the last, the operation will not be carried out, otherwise Pop out of the stack; MaybePop + = canPop;

Case try

// Call maybePop navigator.of (context).maybepop () on PageA and PageB respectively;Copy the code

MaterialApp

Whenever we create a new project, we usually use The MaterialApp as the starting point of runApp(). The MaterialApp is Android-style, and if we want the ios-style, we need CupertinoApp. That is, as a whole application style Widget; By default, widgets such as MaterialApp/CupertinoApp/WidgetApp are embedded in Navigator. The next part will introduce some important properties of MaterialApp.

1. home

Initialize the displayed widgets when entering the application.

class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData(primarySwatch: Colors.blue), initialRoute: '/', onGenerateRoute: generateRoute, home: Scaffold( appBar: AppBar(title: Text('HomePage')), body: Center(child: Text('HomePage')))); }}Copy the code

2. routes

Routes is a static route mapping table of Map

type. When a static route similar to pushNamed is used for page hopping, the corresponding route needs to be bound here first. General default/corresponding root page, of course, we can customize as the name of the other, is usually/system rules, including the Navigator. It was/defaultRouteName corresponding; The rest of the page routing can be hierarchical in a folder style according to the business logic; Xiao CAI used the ARouter plugin in Android native development in a similar way;
,>

Note: Generally, when widgets are displayed in home mode, the root route corresponding to/is not set in the routing table.

3. initialRoute

InitialRoute is used to set the initial startup page. After setting the initial startup page, you do not need to set the home attribute, because the display Widget corresponding to home has a higher priority. If the mapping table on the home page uses the root route corresponding to /, you can omit the initialRoute attribute.

class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData(primarySwatch: Colors.blue), // initialRoute: '/', routes: { '/': (context) => HomePage(title: 'HomePage') }, onGenerateRoute: generateRoute, // home: Scaffold( // appBar: AppBar(title: Text('HomePage')), // body: Center(child: Text('HomePage'))), ); }}Copy the code

4. onGenerateRoute

OnGenerateRoute is a constructor of RouteFactory type. When a static route is used to switch to a page and a page not bound in routes is entered, the onGenerateRoute callback is performed. Generally, during encapsulation, the routes attribute is not set and the service is judged in onGenerateRoute, which is used as the route guard similar to interceptor. This can also be done for public custom route animations.

Function generateRoute = (settings) {
  print('onGenerateRoute -> $settings');
  if (settings == null ||
      settings.name == null ||
      routes[settings.name] == null) {
    return MaterialPageRoute(builder: (context) => routes['/error']());
  } else if (settings.arguments != null) {
    return MaterialPageRoute(
        builder: (context) => routes[settings.name](settings.arguments));
  } else if (settings.name == '/') {
    return MaterialPageRoute(
        builder: (context) => routes[settings.name]('HomePage'));
  } else {
    return MaterialPageRoute(builder: (context) => routes[settings.name]());
  }
};
Copy the code

5. onUnknownRoute

OnUnknownRoute is also a RouteFactory constructor. When a static route is used to jump to a page, it cannot be called back when onGenerateRoute is generated.

6. builder

Builder attribute is often used for MediaQuery device information acquisition or user information preference setting. The MediaQuery tutorial is not a repeat of the MediaQuery tutorial.


For the jump between the pages there are a lot of need to learn and explore the place, xiao CAI suggested to read the source code, learn more excellent tripartite library implementation; If there are mistakes, please give more guidance!

Source: Little Monk A Ce