When I use Navigator.pushNamed(context, "/someRoute");, there is a minimal animation which slides in the new route from the bottom of the screen (on Android, might look different on iOS).
How can I add a custom animation to this transition?
I found this article, which has some very neat sample code for unnamed routes. They implement their own class which inherits from PageRouteBuilder and can be used like this: Navigator.push(context, SlideRightRoute(page: Screen2())). But a PageRouteBuilder is not a Widget and can't be registered as a route in MaterialApp. So I don't see how to apply this to named routes.
You need to use onGenerateRoute in your MaterialApp widget.
onGenerateRoute: (settings) {
if (settings.name == "/someRoute") {
return PageRouteBuilder(
settings: settings, // Pass this to make popUntil(), pushNamedAndRemoveUntil(), works
pageBuilder: (_, __, ___) => SomePage(),
transitionsBuilder: (_, a, __, c) => FadeTransition(opacity: a, child: c)
);
}
// Unknown route
return MaterialPageRoute(builder: (_) => UnknownPage());
},
I found an easy solution (inspired from this code)
First, you need to set a static GlobalKey for MaterialApp and export it
static GlobalKey mtAppKey = GlobalKey();
Widget build(BuildContext context) {
return MaterialApp(
key: MyApp.mtAppKey,
...
Also, you need to a custom PageRouteBuilder to handle it
Null-safety disabled
class CustomNamedPageTransition extends PageRouteBuilder {
CustomNamedPageTransition(
GlobalKey materialAppKey,
String routeName, {
Object arguments,
}) : super(
settings: RouteSettings(
arguments: arguments,
name: routeName,
),
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
assert(materialAppKey.currentWidget != null);
assert(materialAppKey.currentWidget is MaterialApp);
var mtapp = materialAppKey.currentWidget as MaterialApp;
var routes = mtapp.routes;
assert(routes.containsKey(routeName));
return routes[routeName](context);
},
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
FadeTransition(
opacity: animation,
child: child,
),
transitionDuration: Duration(seconds: 1),
);
}
Null-safety enabled
class CustomNamedPageTransition extends PageRouteBuilder {
CustomNamedPageTransition(
GlobalKey materialAppKey,
String routeName, {
Object? arguments,
}) : super(
settings: RouteSettings(
arguments: arguments,
name: routeName,
),
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
assert(materialAppKey.currentWidget != null);
assert(materialAppKey.currentWidget is MaterialApp);
var mtapp = materialAppKey.currentWidget as MaterialApp;
var routes = mtapp.routes;
assert(routes!.containsKey(routeName));
return routes![routeName]!(context);
},
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
FadeTransition(
opacity: animation,
child: child,
),
transitionDuration: Duration(seconds: 1),
);
}
Then, you can open your named route with
Navigator.push(
context,
CustomNamedPageTransition(
MyApp.mtAppKey,
MyRoute.routeName,
),
);
or
Navigator.pushReplacement(
context,
CustomNamedPageTransition(
MyApp.mtAppKey,
MyRoute.routeName,
),
);
Using animated routes is possible without onGenerateRoute!
If you are using MaterialApp's routes map for defining your named routes, here is how you could define a named route (whose name will not be null).
Just create your route by extending PageRouteBuilder:
import 'package:flutter/material.dart';
class FadeInRoute extends PageRouteBuilder {
final Widget page;
FadeInRoute({this.page, String routeName})
: super(
settings: RouteSettings(name: routeName), // set name here
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
FadeTransition(
opacity: animation,
child: child,
),
transitionDuration: Duration(milliseconds: 500),
);
}
and then when you are navigating, just do:
Navigator.push( // or pushReplacement, if you need that
context,
FadeInRoute(
routeName: RouteNames.home,
page: MyHomeScreen(),
),
);
Creating an animated transition and using popUntil with named routes does not require the use of onGenerateRoute. You only need to specify the routeName again when creating the PageRouteBuilder.
Modifying the example from the Flutter docs, maintaining a named reference to a route can be achieved by adding the settings parameter to PageRouteBuilder:
Route _createRoute() {
return PageRouteBuilder(
settings: RouteSettings(name: '/new-screen'),
pageBuilder: (context, animation, _) => const NewScreen(),
transitionsBuilder: (context, animation, _, child) {
const begin = Offset(0.0, 1.0);
const end = Offset.zero;
const curve = Curves.ease;
var tween = Tween(begin: begin, end: end).chain(CurveTween(curve: curve));
return SlideTransition(
position: animation.drive(tween),
child: child,
);
},
);
}
which is simply called using Navigator.of(context).push(_createRoute());
The screen NewScreen can be normally registered under the MaterialApp routes:
MaterialApp(
...
...
routes: {
...
'/new-screen': (context) => NewScreen(),
}
)
You can modify the code above to be more dynamic.
That said, using onGeneratedRoute is a more permanent solution
Related
The bounty expires in 5 days. Answers to this question are eligible for a +100 reputation bounty.
Chris wants to draw more attention to this question.
I have a CustomPageRoute for a fade animation when pushing to another screen. That is working as expected.
However I would love to have a swipe back animation and can not make it work. I tried couple of different things, the most promising was this answer but that ist still sliding in/out the page.
For animation I only want the a fadeAnimation, both for pushing and popping.
This is my code for the FadeTransition:
class FadePageTransition extends Page {
final Widget page;
const FadePageTransition({
required this.page,
LocalKey? key,
String? restorationId,
}) : super(
key: key,
restorationId: restorationId,
);
#override
Route createRoute(BuildContext context) {
return FadeRoute(
child: page,
routeSettings: this,
);
}
}
class FadeRoute<T> extends PageRoute<T> {
final Widget child;
final RouteSettings routeSettings;
FadeRoute({
required this.child,
required this.routeSettings,
});
#override
RouteSettings get settings => routeSettings;
#override
Color? get barrierColor => Palette.black;
#override
String? get barrierLabel => null;
#override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return FadeTransition(
opacity: animation,
child: child,
);
}
#override
bool get maintainState => true;
#override
Duration get transitionDuration => const Duration(
milliseconds: transitionDurationInMS,
);
}
Let me know if you need any more info.
This is my approach for fade in and slide transitions if you can figure out from context if you are adding or removing from route you put condition and that should work.
Future nextScreenSlideIn(BuildContext context, page) {
PageRouteBuilder builder = PageRouteBuilder(
pageBuilder: (_, Animation animation, Animation secondaryAnimation) {
return page;
},
transitionsBuilder: (
_,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(1, 0),
end: Offset.zero,
).animate(animation),
child: child,
);
},
transitionDuration: const Duration(milliseconds: 200));
return Navigator.push(context, builder);
}
Future nextScreenFadeIn(BuildContext context, page) {
PageRouteBuilder builder = PageRouteBuilder(
pageBuilder:
(_, Animation<double> animation, Animation secondaryAnimation) {
return page;
},
transitionsBuilder: (
_,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return FadeTransition(
opacity: Tween<double>(begin: 0, end: 1).animate(animation),
child: child,
);
},
transitionDuration: const Duration(milliseconds: 200));
return Navigator.push(context, builder);
}
or
You can try following package: https://pub.dev/packages/page_transition#do-you-want-use-theme-transitions-
it has also mentioned similar thing.
I am trying to achieve a nice simple fade animation from one navigation route to another using PageRouteBuilder. I want the current route to fade out completely, then after the old route is gone, the new route should fade in.
So far in my PageRouteBuilder class, I can fade the new route in from 0 to 1, but I want the old route to fade out fully first, then after the old route has faded out for the new route to fade in. So far in my current code, the old route disappears suddenly once the new route fading in has finished.
I also want to emphasise that I do not want them to fade out/in at the same time, but for the fade out of the old route then fade in for the new route to happen in sequence.
import 'package:flutter/material.dart';
class FadePageTransition extends PageRouteBuilder {
final Widget child;
FadePageTransition({
required this.child,
}) : super(
transitionDuration: const Duration(milliseconds: 600),
pageBuilder: (context, animation, secondaryAnimation) => child,
);
#override
Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) => FadeTransition(
opacity: animation,
child: child,
);
}
I know that the secondaryAnimation property controls the animation for how the old route leaves, doesn't it? but i'm just not sure how that would work in this context.
Use 2 FadeTransition in transitionBuilder: is the solution to your problem.
If that explanation is kinda hard to understand, this is how you use it.
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return FadeTransition(
opacity: animation,
child: FadeTransition(
opacity: secondaryAnimation,
child: child,
),
);
}
That's it!
You have to make special curves to get this to work.
class DelayedCurve extends Curve {
const DelayedCurve() : super();
#override
double transformInternal(double t) {
if (t < 0.5) {
return 0.0;
} else {
return (t - 0.5) * 2.0;
}
}
}
class CurveDelayed extends Curve {
const CurveDelayed() : super();
#override
double transformInternal(double t) {
if (t > 0.5) {
return 1.0;
} else {
return t * 2;
}
}
}
and you have to drive them correctly.
class FadeFirstTransition extends PageRouteBuilder {
final Widget child;
FadeFirstTransition({
required this.child,
}) : super(
transitionDuration: const Duration(milliseconds: 3000),
reverseTransitionDuration: const Duration(milliseconds: 3000),
pageBuilder: (context, animation, secondaryAnimation) => child,
);
#override
Widget buildTransitions(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) =>
FadeTransition(
opacity: animation.drive(Tween<double>(begin: 0, end: 1)
.chain(CurveTween(curve: const DelayedCurve()))),
child: FadeTransition(
opacity: secondaryAnimation.drive(Tween<double>(begin: 1, end: 0)
.chain(CurveTween(curve: const CurveDelayed()))),
child: child,
));
}
I am trying to use my previous app with the following code, but it seems some updates have happened in Flutter and I get the following Error:
import 'package:flutter/material.dart';
class CustomRoute<T> extends MaterialPageRoute<T> {
CustomRoute({
WidgetBuilder builder,
RouteSettings settings,
}) : super(
builder: builder,
settings: settings,
);
#override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
if (settings.name == '/') {
return child;
}
return FadeTransition(
opacity: animation,
child: child,
);
}
}
class CustomPageTransitionBuilder extends PageTransitionsBuilder {
#override
Widget buildTransitions<T>(
PageRoute<T> route,
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
if (route.settings.name == '/') {
return child;
}
return FadeTransition(
opacity: animation,
child: child,
);
}
}
Error:
The parameter 'builder' can't have a value of 'null' because of its
type, but the implicit default value is 'null'. Try adding either an
explicit non-'null' default value or the 'required' modifier.
I tried to add either required or #required but neither worked.`
can you use like this? because it not gives error:
import 'package:flutter/material.dart';
class CustomRoute<T> extends MaterialPageRoute<T> {
CustomRoute({
required WidgetBuilder builder,
required RouteSettings settings,
}) : super(
builder: builder,
settings: settings,
);
#override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
if (settings.name == '/') {
return child;
}
return FadeTransition(
opacity: animation,
child: child,
);
}
}
class CustomPageTransitionBuilder extends PageTransitionsBuilder {
#override
Widget buildTransitions<T>(
PageRoute<T> route,
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
if (route.settings.name == '/') {
return child;
}
return FadeTransition(
opacity: animation,
child: child,
);
}
}
I tried to add required and it worked.
I have a Router that works likes this:
In the first step there is a MaterialPage being created:
return MaterialPage(
child: SomePage(),
key: keyName,
name: pageName,
arguments: routeSettings.arguments,
);
and added to the array of Pages then notifyListeners() is called. This router class has a build method like this:
return Navigator(
key: navigatorKey,
pages: List.of(_pages),
onPopPage: _onPopPage,
);
Now my question is where can change page transition for some pages in such a setting? I was trying to use page_transition package but it returns a PageTransition object not a Widget which is required in MaterialPage.
You can use a PageRouteBuilder to implement different page transitions. For example a slide animation:
class SlideRoute extends PageRouteBuilder {
final Widget page;
final RouteSettings settings;
SlideRoute({required this.page, required this.settings})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
settings: settings,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
SlideTransition(
position: Tween<Offset>(
begin: const Offset(1, 0),
end: Offset.zero,
).animate(animation),
child: child,
),
);
}
Then you can use this when returning a route, for example with onGenerateRoute of MaterialApp:
MaterialApp(
onGenerateRoute: (settings) {
switch (settings.name) {
case '/route1':
return SlideRoute(page: Route1(), settings: settings);
case '/route2':
return SlideRoute(page: Route2(), settings: settings);
}
},
)
What I am currently doing
Navigator.push(context,
RouteAnimationFadeIn(NewWidget(someValue), true));
RouteAnimationFadeIn:
class RouteAnimationFadeIn extends PageRouteBuilder {
final Widget widget;
final bool shouldMaintainState;
RouteAnimationFadeIn(this.widget, this.shouldMaintainState)
: super(pageBuilder: (BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
return widget;
}, transitionsBuilder: (BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) {
return FadeTransition(
opacity: animation,
child: child,
);
});
#override
bool get maintainState {
return shouldMaintainState;
}
}
This disposes of the previous widget, which consequently disposes of data of all the form fields in it. What I want is a fragment add like the functionality of Android, so that the new widget opens on tap of the old widget so that, when I use Navigator.pop(context); I see the old data in it.
I tried this, but it doesn't work.