Flutter Navigator 2.0 页面过渡
Posted
技术标签:
【中文标题】Flutter Navigator 2.0 页面过渡【英文标题】:Flutter Navigator 2.0 page transition 【发布时间】:2021-06-22 02:37:35 【问题描述】:我正在使用 Navigator 的声明式方法:
Navigator(
pages: [
MaterialPage(child: _screen),
],
onPopPage: (route, result)
return route.didPop(result);
,
);
如何在屏幕之间添加过渡?
【问题讨论】:
【参考方案1】:您可以在您的应用的theme
属性中设置pageTransitionsTheme
。
例如:
void main()
runApp(
MaterialApp(
routes:
'/': (_) => HomePage(),
'/page2': (_) => Page2(),
,
theme: ThemeData(
pageTransitionsTheme: PageTransitionsTheme(
builders:
// Set your transitions here:
TargetPlatform.android: CupertinoPageTransitionsBuilder(),
TargetPlatform.ios: FadeUpwardsPageTransitionsBuilder(),
TargetPlatform.macOS: FadeUpwardsPageTransitionsBuilder(),
,
),
),
),
);
但正如您提到的,您正在使用 routemaster
包(我个人从未使用过),您仍然可以通过执行以下操作来实现该行为:
MaterialApp.router(
routerDelegate: RoutemasterDelegate(routesBuilder: (_) => routes),
routeInformationParser: RoutemasterParser(),
theme: ThemeData.dark().copyWith(
pageTransitionsTheme: PageTransitionsTheme(
builders:
// Set your transitions here:
TargetPlatform.android: CupertinoPageTransitionsBuilder(),
TargetPlatform.iOS: FadeUpwardsPageTransitionsBuilder(),
TargetPlatform.macOS: FadeUpwardsPageTransitionsBuilder(),
,
),
),
)
完整代码(使用routemaster
包)
void main() => runApp(MyApp());
final routes = RouteMap(
routes:
'/': (_) => MaterialPage(child: HomePage()),
'/page2': (_) => MaterialPage(child: Page2()),
,
);
class MyApp extends StatelessWidget
@override
Widget build(BuildContext context)
return
MaterialApp.router(
routerDelegate: RoutemasterDelegate(routesBuilder: (_) => routes),
routeInformationParser: RoutemasterParser(),
theme: ThemeData(
pageTransitionsTheme: PageTransitionsTheme(
builders:
// Set your transitions here:
TargetPlatform.android: CupertinoPageTransitionsBuilder(),
TargetPlatform.iOS: FadeUpwardsPageTransitionsBuilder(),
TargetPlatform.macOS: FadeUpwardsPageTransitionsBuilder(),
,
),
),
);
class HomePage extends StatelessWidget
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(title: Text('HomePage')),
body: Center(
child: ElevatedButton(
onPressed: () => Routemaster.of(context).push('/page2'),
child: Text('Page2'),
),
),
);
class Page2 extends StatelessWidget
@override
Widget build(BuildContext context) => Scaffold(appBar: AppBar(title: Text('Page2')));
【讨论】:
【参考方案2】:在https://pub.dev/packages/page_transition使用这个包page_transition
onGenerateRoute: (settings)
switch (settings.name)
case '/second':
return PageTransition(child: SecondPage(), type: PageTransitionType.scale);
break;
default:
return null;
,
【讨论】:
以上是关于Flutter Navigator 2.0 页面过渡的主要内容,如果未能解决你的问题,请参考以下文章
为啥 Flutter Navigator 2.0 示例中没有返回按钮?