我通过Luca的存储库将Firebase、riverpod和Gor外层组合在一起。真的很好用。现在我的问题是,我正在制作一个web应用程序,我不知道如何访问位于GoRouter中的routerProvider路由,以便在用户单击导航项时更改页面。这似乎是个简单的问题,但我以前在导航和全局键方面遇到过问题。
我已经将我的代码简化为我认为最重要的部分,但是如果需要更多的部分,请告诉我。我的routerProvider是基于我的auth,它利用Firebase。
`final routerProvider = Provider<GoRouter>((ref) {
final authState = ref.watch(authStateProvider);
return GoRouter(
navigatorKey: key,
debugLogDiagnostics: true,
initialLocation: SplashPage.routeLocation,
routes: [
GoRoute(
path: SplashPage.routeLocation,
name: SplashPage.routeName,
builder: (context, state) {
return const SplashPage();
},
),
GoRoute(
path: '/preloginhome',
name: 'preloginhome',
builder: (context, state) {
return const PreLoginHome();
},
),
GoRoute(
path: '/dashboard',
name: 'dashboard',
builder: (context, state) {
return const Dashboard();
},
),
//more code主应用程序监视上面的routerProvider‘
class MyAppWithFirebase extends ConsumerWidget {
const MyAppWithFirebase({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final router = ref.watch(routerProvider);
return MaterialApp.router(
theme: CustomTheme.darkTheme,
routeInformationParser: router.routeInformationParser,
routerDelegate: router.routerDelegate,
routeInformationProvider: router.routeInformationProvider,
);
}
}现在我的问题是,如何使用在routerProvider中声明的路由导航?我的自定义应用程序栏是这样的,但我遗漏了一些东西。
class CustomAppBar extends ConsumerWidget implements PreferredSizeWidget {
const CustomAppBar({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final router = ref.watch(routerProvider);
final isUserSignedIn = FirebaseAuth.instance.currentUser != null;
return AppBar(
title: TextButton(
onPressed: isUserSignedIn
? () {
key.currentState!.pushNamed(Dashboard.routeLocation);
}
: () {
key.currentState!.pushNamed('/preloginhome');
},
child: Text(
'Agroopet',
style: TextStyle(
fontSize: 22,
color: Theme.of(context).colorScheme.onSurface,
),
),
),只是不知道如何正确访问routerProvider中的路由,也不正确地设置全局导航键。
使用上面的代码,我得到了错误
“引发了另一个异常: Navigator.onGenerateRoute为null,但引用了名为"/preloginhome”的路由。“
发布于 2022-11-14 19:50:32
从文档中,要导航到页面,可以使用GoRouter.of(context).go('/page2')、context.go('/page2')或context.push('/page2')。
看看这个医生来了
发布于 2022-11-17 10:38:13
这个问题甚至没有以正确的方式提出。现在我已经取得了一些进展,当我能够在登录时导航(我正在测试,而不是身份验证)时,我可以这样调用routerProvider:
onPressed: isUserSignedIn
? () => ref.read(routerProvider).go(Dashboard.routeLocation)
: () {
ref.read(routerProvider).go(PreLoginHome.routeLocation);
},现在,问题似乎出现在我自己的AuthChecker类中,因为当用户未经身份验证时,除了登录屏幕之外,我什么也不能去。
class AuthChecker extends ConsumerWidget {
const AuthChecker({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final authState = ref.watch(authStateProvider);
return authState.when(
data: (user) {
if (user != null) return const Dashboard();
return const LoginPage();
},
loading: () => const LoadingScreen(),
error: (e, trace) => ErrorScreen(e, trace));
}
}https://stackoverflow.com/questions/74436263
复制相似问题