问题描述
我知道如何创建滑动效果,但是它只能在当前页面上的页面中滑动,这是通过以下代码完成的:
Navigator.push(context,_createRoute());
Route _createRoute() {
return PageRouteBuilder(
pageBuilder: (context,animation,secondaryAnimation) => PageTwo(),transitionDuration: Duration(milliseconds: 500),transitionsBuilder: (context,secondaryAnimation,child) {
var begin = Offset(1.0,0.0);
var end = Offset.zero;
var curve = Curves.eaSEOut;
var tween = Tween(begin: begin,end: end);
var curvedAnimation = CurvedAnimation(
parent: animation,curve: curve,reverseCurve: curve,);
return SlideTransition(
position: tween.animate(curvedAnimation),child: child,);
});
}
解决方法
您可以通过扩展PageRouteBuilder来为过渡动画创建新的类,还可以避免重复,以后可以重用过渡。
第一个创建类:
class MyTransition extends PageRouteBuilder {
final Widget oldScreen;
final Widget newScreen;
MyTransition({this.oldScreen,this.newScreen})
: super(
pageBuilder: (
BuildContext context,Animation<double> animation,Animation<double> secondaryAnimation,) =>
newScreen,transitionsBuilder: (
BuildContext context,Widget child,) =>
Stack(
children: <Widget>[
SlideTransition(
position: new Tween<Offset>(
begin: const Offset(0.0,0.0),end: const Offset(-1.0,).animate(animation),child: oldScreen,),SlideTransition(
position: new Tween<Offset>(
begin: const Offset(1.0,end: Offset.zero,child: newScreen,)
],);
}
请注意,使用堆栈来管理同一位置上的两个动画。然后只需使用slideTransition。
之后,您只需在需要转换的地方调用它即可
Navigator.push(
context,MyTransition(
oldScreen: this,newScreen: PageTwo(),);
),