flutter: animate transition to named route
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(),
),
);
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());
},