tezvyn:

MaterialPageRoute: The Page in Your Navigator Stack

AI-drafted, machine-checkedSource: api.flutter.devbeginner

Think of Navigator as a stack of screens. MaterialPageRoute wraps your new screen widget, defining its platform-specific transition (slide on iOS, zoom on Android). You use it with `Navigator.push` to show a new screen.

WHY IT EXISTS Apps need to move between different screens. Simply swapping widgets is jarring and loses state. Flutter needed a standard way to manage a stack of screens with platform-appropriate animations and lifecycle management for routes that are no longer visible but might be returned to.

THE MENTAL MODEL Think of the Navigator as a stack of plates. Each plate is a MaterialPageRoute that holds the content (your widget) for one screen. When you want to show a new screen, you push a new plate onto the stack. When you go back, you pop the top plate off, revealing the one underneath.

HOW IT WORKS You create a MaterialPageRoute instance, providing a builder function that returns the widget for your new screen. You then pass this route to Navigator.push(). Flutter renders the new widget and animates the transition based on the platform: a zoom-and-fade for Android, a slide from the right for iOS. When you call Navigator.pop(), the process reverses. You can also pass a result back to the previous screen when popping a route.

WHEN TO USE IT This is the default, go-to solution for full-screen navigation in a Material app. Use it whenever you need to move from one distinct screen to another, like from a product list to a product detail page, or from a login screen to the home screen.

WHEN NOT TO USE IT Don't use it for UI changes that aren't full-screen transitions, like showing a dialog, a bottom sheet, or a snackbar; Flutter has specific functions for those (e.g., showDialog). For highly custom transitions, you might create your own PageRoute subclass instead of using MaterialPageRoute directly.

ONE CANONICAL EXAMPLE The most common pattern is pushing a new route. To navigate to a SecondScreen widget, you call: Navigator.push(context, MaterialPageRoute(builder: (context) => SecondScreen()));. The key parts are the Navigator.push method and the MaterialPageRoute which takes a builder to construct the destination widget. The footgun to remember is that the previous screen remains in memory by default because maintainState is true. If you have a deep navigation stack and want to free resources, you can use Navigator.pushReplacement to replace the current screen instead of adding to the stack, or configure maintainState to be false.

Read the original → api.flutter.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.