Flutter Navigation 1.0 — Routing made easy
We all have to do it at some point: navigating from one screen to the next. How do you handle navigation in a Flutter project? Let’s look at basic navigation, how we can keep it maintainable throughout the project and how we pass data to and from a screen in our Flutter app.
So, you’d like to navigate from one screen to the next? Since everything in Flutter is a widget… Yep, you’d guessed it, we have a widget for that 😄.
Navigator widget handles navigation within our Flutter app. Your screens are basically full-screen widgets, so the
Navigator is nothing more than a
StatefulWidget handling child widgets in a stack. The stack starts off with the
home widget we define in our
MaterialApp and depending on how our project looks we then push new screens on top of that. The
Navigator's a bit more complex under the hood, but that’s for another time. Don’t hesitate if you’d like to check out the source code though!
Now, let’s say we have a
ListScreen and we’d like to navigate to the
DetailScreen. The simplest way to do so would be to call the
Navigator from the
ListScreen and tell it to push a new
DetailScreen. That would look something like this:
The code’s fairly straightforward: we ask the
push a new screen, we pass the current
context as well as a new
MaterialPageRoute as parameters and then simply return the screen we want to navigate to from the Page route’s
builder method. That’s it!
Now that we’re on the detail screen, how do we actually navigate back to the list? For that, we can ask the
pop the screen instead: