The Ultimate Guide to GoRouter: Navigation in Flutter Apps Part -3 (Custom Transitions)
Part -1: https://tinyurl.com/k3f64hwv
Part -2: https://tinyurl.com/3azk6jjj
Starting with custom transitions in GoRouter is a fantastic way to enhance the user experience of our Flutter application by adding visually appealing and smooth animations between routes.
GoRouter allows us to specify custom transitions using the pageBuilder
instead of the basic builder
. This enables us to define custom animations for each route transition.
Custom Transitions
Step 1: Define the CustomTransition by CustomTransitionPage Widget
You’ll need to create a CustomTransitionPage
which is essentially a Page
that allows you to define transitions. Here’s a basic implementation:
import 'package:flutter/material.dart';
class CustomTransitionPage extends Page {
final Widget child;
final Duration transitionDuration;
final RouteTransitionsBuilder transitionsBuilder;
CustomTransitionPage({
required this.child,
this.transitionDuration = const Duration(milliseconds: 300),
required this.transitionsBuilder,
}) : super(key: ValueKey(child));
@override
Route createRoute(BuildContext context) {
return PageRouteBuilder(
settings: this,
pageBuilder: (context, animation, secondaryAnimation) => child,
transitionDuration: transitionDuration,
transitionsBuilder: transitionsBuilder,
);
}
}
Step 2: Add CustomTransition to our DetailsPage
So let's setup our pageBuilder
for our to implement it in our app_router.dart
GoRoute(
path: '/details/:itemId',
//This is Where custom Transition is used
pageBuilder: (BuildContext context, GoRouterState state) {
final params = state.pathParameters['itemId'];
final int itemId = int.tryParse(params ?? '') ?? 0;
return CustomTransitionPage(
key: state.pageKey,
child: DetailsPage(itemId: itemId),
//We are using Fade Transition here
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return FadeTransition(opacity: animation, child: child);
},
);
}
),
Key Updates
- Custom Transition for DetailsPage: The route now uses
pageBuilder
with aFadeTransition
to provide a smooth fade-in effect when navigating to theDetailsPage
.
So let's test the transition
If you want to see a prolonged animation. Then you can adjust the transitionDuration
and get see the detailed animation.
Perfect. Now you know enough about GoRouter to work on any app that you need.
I'll be creating a new series on GoRouter + Riverpod . Which will cover Authentication, Preloading Data, Advanced Deep Linking with Firebase and everything in between. So stay tuned and subscribe to my blog.
Subscribe to my newsletter
Read articles from Harish Kunchala directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by