在Android API上,我们可以使用
overridePendingTransition(int enterAnim, int exitAnim)
定义进入和退出转换。
如何在Flutter中做到这一点?
我已经实现了这段代码
class SlideLeftRoute extends PageRouteBuilder {
final Widget enterWidget;
SlideLeftRoute({this.enterWidget})
: super(
pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
return enterWidget;
},
transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
return SlideTransition(
position: new Tween<Offset>(
begin: const Offset(1.0, 0.0),
end: Offset.zero,
).animate(animation),
child: child
);
},
);
}
但它仅定义输入转换。如何定义退出转场?
更新
想象一下,当我执行时,我有两个屏幕(Screen1和Screen2)
Navigator.push(
context, SlideLeftRoute(enterWidget: Screen2()));
我想将动画应用于Screen1和Screen2,而不仅是Screen2
example
最佳答案
我使用了不同的方式,但是diegodeveloper提供了类似的逻辑
截屏:
完整的代码:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Page1(),
);
}
}
class Page1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Page 1"),
leading: Icon(Icons.menu),
),
body: Container(
color: Colors.grey,
child: Center(
child: RaisedButton(
onPressed: () => Navigator.push(context, MyCustomPageRoute(previousPage: this, builder: (context) => Page2())),
child: Text("2nd Page"),
),
),
),
);
}
}
class Page2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Page 2")),
body: Container(
color: Colors.blueGrey,
child: Center(
child: RaisedButton(
onPressed: () => Navigator.pop(context),
child: Text("Back"),
),
),
),
);
}
}
class MyCustomPageRoute extends MaterialPageRoute {
final Widget previousPage;
MyCustomPageRoute({this.previousPage, WidgetBuilder builder, RouteSettings settings}) : super(builder: builder, settings: settings);
@override
Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget currentPage) {
Animation<Offset> _slideAnimationPage1 = Tween<Offset>(begin: Offset(0.0, 0.0), end: Offset(-1.0, 0.0)).animate(animation);
Animation<Offset> _slideAnimationPage2 = Tween<Offset>(begin: Offset(1.0, 0.0), end: Offset(0.0, 0.0)).animate(animation);
return Stack(
children: <Widget>[
SlideTransition(position: _slideAnimationPage1, child: previousPage),
SlideTransition(position: _slideAnimationPage2, child: currentPage),
],
);
}
}