Home > other >  Using `home` property with `initialRoute` in MaterialApp
Using `home` property with `initialRoute` in MaterialApp

Time:10-31

Could you explaine how does this navigation works?

Why the app start starts with the LoginPage opened? Does it mean that initialRoute property shadow the home property in the MaterialApp?

If to make pop from the LoginPage then the HomePage will be opened. Does it mean that HomePage was opened before the initialRoute was launched?

return MaterialApp(
      home: const HomePage(),
      initialRoute: '/login',
      onGenerateRoute: _getRoute,
);

Route<dynamic>? _getRoute(RouteSettings settings) {
    if (settings.name != '/login') {
      return null;
    }

    return MaterialPageRoute<void>(
      settings: settings,
      builder: (BuildContext context) => const LoginPage(),
      fullscreenDialog: true,
    );
}

That is shown here https://github.com/material-components/material-components-flutter-codelabs/blob/102-starter_and_101-complete/mdc_100_series/lib/app.dart

CodePudding user response:

As stated in the official documentation, we should use either the initialRoute or the home property:

 Warning: When using initialRoute, don’t define a home property.

Source

CodePudding user response:

About the home property

The widget for the default route of the app (Navigator.defaultRouteName, which is /).
This is the route that is displayed first when the application is started normally, unless initialRoute is specified. It's also the route that's displayed if the initialRoute can't be displayed.

But more interesting thing is about pop and from the doc

If the route name starts with a slash, then it is treated as a "deep link", and before this route is pushed, the routes leading to this one are pushed also. For example, if the route was /a/b/c, then the app would start with the four routes /, /a, /a/b, and /a/b/c loaded, in that order. Even if the route was just /a, the app would start with / and /a loaded. You can use the onGenerateInitialRoutes property to override this behavior.

My understanding is app is starting with initialRoute, while the homeproperty is also treat like root /, on last pop it will be at home.

You can also check Navigator always start with route '/'

The MaterialApp configures the top-level Navigator to search for routes in the following order:

  1. For the / route, the home property, if non-null, is used.

  2. Otherwise, the routes table is used, if it has an entry for the route.

  3. Otherwise, onGenerateRoute is called, if provided. It should return a non-null value for any valid route not handled by home and routes.

  4. Finally if all else fails onUnknownRoute is called.

  • Related