Widget build(BuildContext context) {
return Scaffold(
backgroundColor: codGray,
body: Navigator(
key: _navigatorKey,
initialRoute: '/',
onGenerateRoute: (RouteSettings settings) {
WidgetBuilder builder;
// Manage your route names here
switch (settings.name) {
case '/':
builder = (BuildContext context) => ProviderPage();
break;
case '/chats':
builder = (BuildContext context) => ChatProviderPage();
break;
case '/addPoll':
builder = (BuildContext context) => AddPollPage();
break;
case '/friends':
builder = (BuildContext context) => ProfileProviderPage();
break;
case '/settings':
builder = (BuildContext context) => SettingsProviderPage();
break;
default:
throw Exception('Invalid route: ${settings.name}');
}
return MaterialPageRoute(
builder: builder,
settings: settings,
);
},
),
}
这是我的项目的一个片段,我试图在页面之间过渡时实现自定义的动画,但是由于我使用自定义的导航器进行路由,而导航器使用WidgetBuilder,我不知道如何实现自定义的PageRouteBuilder(),它使用WidgetBuilder构建器在页面之间过渡。
你可以通过直接返回 MaterialPageRoute
或 PageRouteBuilder
像这样。
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: codGray,
body: Navigator(
key: _navigatorKey,
initialRoute: '/',
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute(
builder: (BuildContext context) => ProviderPage(),
settings: settings,
);
case '/chats':
return MaterialPageRoute(
builder: (BuildContext context) => ChatProviderPage(),
settings: settings,
);
case '/customTransition':
return PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) => Page(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return child;
},
);
default:
throw Exception('Invalid route: ${settings.name}');
}
},
),
}
虽然你可以在这里重构很多东西,使它更易读和维护。
onGenerateRoute
争论中 Navigator
小部件PageRouteBuilder
与你自己的班级,这需要一个子论点的 Widget
类型,其余所有的转换逻辑都在该类中。