tezvyn:

PageRouteBuilder: Custom Routes Without the Boilerplate

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

PageRouteBuilder creates a custom page route on the fly, skipping the boilerplate of a full subclass. Just provide a `pageBuilder` for the screen's content and a `transitionsBuilder` for a unique animation.

WHY IT EXISTS In Flutter, customizing a page transition normally requires creating a whole new class that extends PageRoute. This is verbose and adds boilerplate for what might be a simple, one-time custom animation. PageRouteBuilder was created to solve this by letting you define a route's behavior with inline functions instead of a new class.

THE MENTAL MODEL Think of PageRouteBuilder as a factory for custom routes. Instead of building the entire factory from scratch by subclassing PageRoute, you use a pre-built one and just supply the two most important parts as instructions: a function to build the page's content (pageBuilder) and a function to build its transition animation (transitionsBuilder). It's a declarative, callback-based approach for one-off routes.

HOW IT WORKS When you call Navigator.push, you pass an instance of PageRouteBuilder. You must provide the required pageBuilder function, which receives the context and animation objects and returns the widget for the new page. To add a custom animation, you also provide a transitionsBuilder. This function receives the context, animations, and the child widget from pageBuilder, allowing you to wrap the child in Transition widgets like FadeTransition or SlideTransition. You can also configure properties like transitionDuration, opaque, and barrierColor directly in the constructor.

WHEN TO USE IT Use PageRouteBuilder when you need a unique, non-standard page transition for a single screen. It's perfect for prototyping different animations quickly or for implementing a special effect that doesn't appear anywhere else in your app, such as a custom modal presentation or a complex coordinated animation.

WHEN NOT TO USE IT Avoid PageRouteBuilder for transitions that are used repeatedly throughout your application. If you have a standard "fade route" or "slide-up route" used in many places, defining it once in a dedicated subclass of PageRoute is much cleaner and more maintainable. Using PageRouteBuilder for every common case leads to significant code duplication.

ONE CANONICAL EXAMPLE To navigate to a new screen with a simple fade-in animation, you call Navigator.push with a PageRouteBuilder. The pageBuilder returns your new screen widget, e.g., NewScreen(). The transitionsBuilder takes the animation and child arguments and returns a FadeTransition(opacity: animation, child: child). You can also set transitionDuration to control the speed of the fade.

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.