Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Navigator: Dynamic initial route

My app displays some introduction screens only on the first launch of the app. After the first launch the first screen to display should be my HomePage. I tried these routes:

"/" -> HomePage()
"/intro" -> IntroPage()

and then set the initialRoute like that:

initialRoute: isFirstLaunch ? "/intro" : "/"

With that configuration Flutter first puts the HomePage() on the navigation stack and the IntroPage() on top, when the initialRoute is "/intro". This is bad, because HomePage() loads a CameraPreview, so it asks for permissions and is resource intensive. It shouldn't be loaded until I navigate to home explicitly.

I also tried this configuration:

"/" -> IntroPage()
"/home" -> HomePage()

Then I have the IntroPage() on by back stack, which is also not what I want.

Any idea how to solve it?

like image 921
hendra Avatar asked Aug 19 '18 08:08

hendra


People also ask

What is onGenerateRoute in Flutter?

onGenerateRoute. The route generator callback used when the app is navigated to a named route. If this returns null when building the routes to handle the specified initialRoute, then all the routes are discarded and Navigator. defaultRouteName is used instead ( / ). See initialRoute.

How do I route to the same page in Flutter?

If the new page is the same as the current page then use Navigator. push(context,route) . If the new page is the different then use Navigator. pushReplacement(context,route) .


2 Answers

The documentation for MaterialApp's initialRoute property explains this behavior as follows:

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.

like image 126
Sebastian Engel Avatar answered Sep 19 '22 07:09

Sebastian Engel


"intro": (BuildContext context) => IntroPage()
"home": (BuildContext context) => HomePage()

makes sure that both routes are top-level routes without a parent.

like image 29
boformer Avatar answered Sep 18 '22 07:09

boformer