Flutter firebase_ui_oauth插件:登录后如何跳转至自定义主页?
问题:Firebase UI OAuth认证完成后跳转自定义应用主页
原Firebase原生认证插件已弃用,重构为firebase_ui_oauth插件后,无法从官方示例中得知如何在认证完成后跳转至自定义的MyHomePage。
核心修改思路
官方示例中认证成功后默认跳转到/profile路由对应的ProfileScreen,我们只需要把所有认证成功后的跳转目标替换为自定义主页即可。
具体修改步骤
1. 添加自定义主页的路由配置
在MaterialApp的routes集合中,新增自定义主页的路由:
routes: { // 保留原有所有路由配置... '/home': (context) { final currentUser = FirebaseAuth.instance.currentUser; return MyHomePage(userId: currentUser!.uid); }, },
2. 修改初始路由判断逻辑
当用户已登录且邮箱已验证时,直接将初始路由指向自定义主页:
String get initialRoute { final auth = FirebaseAuth.instance; if (auth.currentUser == null) { return '/'; } if (!auth.currentUser!.emailVerified && auth.currentUser!.email != null) { return '/verify-email'; } // 替换原有的'/profile'为自定义主页路由'/home' return '/home'; }
3. 修改所有认证成功后的跳转逻辑
找到以下几处认证成功的跳转代码,将目标路由从/profile改为/home:
(1)SignInScreen内的状态监听
AuthStateChangeAction<SignedIn>((context, state) { if (!state.user!.emailVerified) { Navigator.pushNamed(context, '/verify-email'); } else { Navigator.pushReplacementNamed(context, '/home'); } }), AuthStateChangeAction<UserCreated>((context, state) { if (!state.credential.user!.emailVerified) { Navigator.pushNamed(context, '/verify-email'); } else { Navigator.pushReplacementNamed(context, '/home'); } }), AuthStateChangeAction<CredentialLinked>((context, state) { if (!state.user.emailVerified) { Navigator.pushNamed(context, '/verify-email'); } else { Navigator.pushReplacementNamed(context, '/home'); } }),
(2)EmailVerificationScreen内的验证成功跳转
EmailVerifiedAction(() { Navigator.pushReplacementNamed(context, '/home'); }),
(3)SMSCodeInputScreen内的登录成功跳转
AuthStateChangeAction<SignedIn>((context, state) { Navigator.of(context).pushReplacementNamed('/home'); })
可选:直接跳转无需路由名
如果不想通过路由名跳转,也可以直接导航到MyHomePage,示例:
Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => MyHomePage(userId: state.user!.uid), ), );
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

