我目前正在努力使用go_router重构我的路由代码。
我已经有了一些简单的路由,例如/signin& /signup,但是当我尝试使用具有多个屏幕的 BottomNavigationBar 进行路由时,问题就出现了。我想为他们每个人都有一条单独的路线,例如/home, /events& /profile。
我发现我必须以某种方式返回具有不同参数的相同小部件,以防止在按下 BottomNavigationBarItem 时整个屏幕发生变化,而只更新 BottomNavigationBar 上方的部分,这将是屏幕本身。
我想出了一个非常棘手的解决方案:
GoRoute(
path: '/:path',
builder: (BuildContext context, GoRouterState state) {
final String path = state.params['path']!;
if (path == 'signin') {
return const SignInScreen();
}
if (path == 'signup') {
return const SignUpScreen();
}
if (path == 'forgot-password') {
return const ForgotPasswordScreen();
}
// Otherwise it has to be the ScreenWithBottomBar
final int index = getIndexFromPath(path);
if (index != -1) {
return MainScreen(selectedIndex: index);
}
return const ErrorScreen();
}
)
这看起来不太好,并且无法添加类似/profile/settings/appearanceor的子路由/events/:id。
我想要一些像这样容易理解的东西:
GoRoute(
path: '/signin',
builder: (BuildContext context, GoRouterState state) {
return const SignInScreen();
}
),
GoRoute(
path: '/signup',
builder: (BuildContext context, GoRouterState state) {
return const SignUpScreen();
}
),
GoRoute(
path: '/home',
builder: (BuildContext context, GoRouterState state) {
return const ScreenWithNavBar(selectedScreen: 1);
}
),
GoRoute(
path: '/events',
builder: (BuildContext context, GoRouterState state) {
return const ScreenWithNavBar(selectedScreen: 2);
},
routes: <GoRoute>[
GoRoute(
path: ':id',
builder: (BuildContext context, GoRouterState state) {
return const EventScreen();
}
)
]
)
有没有办法实现这种行为?