lgvaz
lgvaz

Reputation: 522

Navigator always start with route '/'

The route '/' keeps being automatically pushed to the Navigator on the start of the application.

Let's start with this example of the official docs.

Everything works fine but if you change '/' to '/home' (change made both to initiaRoute and routes) we get the following error:

The requested route name was: "/home"
The following routes were therefore attempted:
* /
* /home
This resulted in the following objects:
* null
* MaterialPageRoute<dynamic>(RouteSettings("/home", null), animation: null)
 One or more of those objects was null, and therefore the initial route specified will be ignored and
"/" will be used instead.

Question 1: I'm explicitly defining '/home' as the initialRoute, why it's insisting to go to '/'?


I tried to fix the error by adding a blank page for '/'.
The error was 'fixed' and the app was starting on the correct page, but the widget tree was looking like this:
widget_tree

Container is the "blank page" I created associated with '/' and still being pushed. For even more confusion it's on the top of the navigation stack!

Question 2: Why FirstScreen is being shown instead of Container?

Upvotes: 7

Views: 2993

Answers (2)

JerryZhou
JerryZhou

Reputation: 5206

Actually it's kind of design as PR mentioned.

The main purpose of this PR is to make it so that when you set the initial route and it's a hierarchical route (e.g. /a/b/c), it implies multiple pushes, one for each step of the route (so in that case, /, /a, /a/b, and /a/b/c, in that order). If any of those routes don't exist, it falls back to '/'.

Upvotes: 2

Derek Lakin
Derek Lakin

Reputation: 16319

This caught me out, too. If you look at the documentation for the initialRoute property:

If the route contains slashes, 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 three routes /a, /a/b, and /a/b/c loaded, in that order.

What the example fails to explain is that / is also pushed. So if your initialRoute is /home then it first pushes /, then it pushes /home.

The (thankfully very simple) fix is to use routes that don't start with /, so in your case, just home :)

Upvotes: 14

Related Questions