Recently, in my new project, I encountered a very strange issue when working with Flutter Navigation.
Let’s get straight to the point; I will jump directly into the main content. Please take a look at the following code related to Flutter routing:
Do you see the initialRoute value?
It directs to the login page of the main application because I wanted to show the Login screen as the first screen when someone opens the app.
Thinking the same, I decided to direct my application to the “/login” page, making it the initial route.
Pretty straightforward scenario, right?
WRONG.
Unfortunately, it did not work as I expected.
I mean, it can send users to the login screen, but not in the same way as I wanted.
Let me explain the issue clearly: Though the login screen opened, it was showing a back button on the AppBar. This allowed the user to go back from the same screen even after logging in. Why is this happening?
You would say, “There must be something wrong with the AppRoutes.generateRoute method.” Well, I don’t think so. I have checked the code several times to make sure that everything is correct.
Do you still have doubts? Please take a look at this:
It seems okay, doesn’t it?
Yes, it seemed okay when you checked for the break and return keywords in the places where they should be.
So what was happening? Why was this Login screen showing the back button?
I investigated further and found the answer, of course.
I checked the source code and found this in navigator.dart above the defaultGenerateInitialRoutes method.
If this string starts with a `/` character and has multiple `/` characters
in it, then the string is split on those characters and substrings from
the start of the string up to each such character are, in turn, used as
routes to push.
So, the Flutter initialRoute method is the culprit, or maybe it’s just my negligence.
What happened was, when I wrote “/login”, it was split based on the slash “/” and the two routes were pushed into the navigator stack: root and login.
Yes, this is how the Flutter navigator works.
Learn how to build a complex navigation stack with Flutter.
So, how do we correct the issue?
Well, as you can guess, I just need to remove this “/” (slash) symbol from the initial path’s value. Everything will be sorted.
Did you imagine how a slash can make or break things in the Flutter code? Neither did I.
However, I am glad that I was able to figure it out.
—
Now you know something new about Flutter Navigator, don’t you? Happy coding!