Now, what if we want to programmatically push routes to the Navigator using the animations we’ve covered so far? Well, these transitions are just good ol’ page transitions. So we could use them as transitions for PageRouteBuilders. With this approach, we could simply call the push method and pass in our custom transitions.
To implement this, I’ve created a class in the stater project for this episode. Open up the motion_route.dart file inside the widgets folder. It might look intimidating at first but these are just static builders methods inside a class. Let’s break down one of them.
I’ll scroll to the sharedAxis method below. You can see that this static method returns a PageRouteBuilder. Then the transitionBuilder returns a SharedAxisTransition widget. Now, let’s talk about the arguments of the sharedAxis method.
It has a required argument named ‘page’, which is the page we want to navigate to. Next, it has a set of optional arguments. The first item is the type, which is used to specify the SharedAxisTransitionType. Here, i’ve given it a default type of scaled. And finally, we have the duration argument used to specify the duration.
The same approach applies for the other static methods of this class. The main difference is the transition returned from the transitionsBuilder callback. Cool, now let’s make use of this class.
We want to open up the article image in a new page. Head over to the article_page.dart file. Scroll down to the the header image of the article which is located inside the FlexibleSpaceBar.
The image we have here is the image displayed in the top section of the detail page.
We want to open it up in a new page to show its full size. Go ahead and wrap the image widget with an InkWell widget to make it tappable. Then inside the onTap callback function, enter the folllowing code:
flexibleSpace: FlexibleSpaceBar(
background: InkWell(
onTap: () {
Navigator.push<void>(
context,
MaterialMotionRoutes.sharedAxis(
ArticleImage(article!.urlToImage),
),
);
},
child: Image.network(
...
In here, we have push method and instead of passsing the usual MaterialPageRoute, we pass the
MaterialMotionRoutes.sharedAxis() method we created. And for the page to naviagte to, we pass in the ArticleImage widget. The ArticleImage widget is also included in the starter project for this episode.
Save your work and try it out. Cool, we see the article image scales out to fill the screen. We can change the transition type to horizontal, thanks to the optional argument list provided by the method. Let’s add that now:
...
MaterialMotionRoutes.sharedAxis(
ArticleImage(article!.urlToImage),
SharedAxisTransitionType.horizontal // New code
),
Save your work. And you can see the article image slides in on the horizontal axis. The MotionRoutes class has other route transitions in it. I’ll leave you to try them out.