You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

登录后无法跳转至BottomNavbar页面,卡在启动页求助

问题诊断与解决方案

你的应用卡在启动页无法跳转,核心原因有两个:

  1. 启动页未触发认证状态检查:SplashScreen仅监听LoginCubit的状态变化,但没有主动调用checkAuthenticationStatus()方法,导致Cubit不会执行用户认证状态的检查流程,始终停留在初始状态,listener无法触发页面跳转。
  2. 同步获取用户状态存在延迟:getCurrentUser()是同步方法,Firebase Auth初始化完成前,currentUser可能返回null,无法准确判断用户是否已登录。

修复步骤

1. 修改SplashScreen为StatefulWidget,主动触发认证检查

将Stateless的SplashScreen改为Stateful,在initState中调用Cubit的检查方法:

class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    // 触发用户认证状态检查
    context.read<LoginCubit>().checkAuthenticationStatus();
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<LoginCubit, LoginState>(
      listener: (context, state) {
        if (state is LoginSuccess) {
          context.goNamed(AppRoutes.bottomNavBarRoute);
        } else if (state is LoginFailure || state is LoginInitial) {
          // 未登录或认证失败时跳转到登录页
          context.goNamed(AppRoutes.loginRoute);
        }
      },
      child: const Scaffold(
        body: Center(
          child: CircularProgressIndicator(
            color: Colors.red,
          ),
        ),
      ),
    );
  }
}

2. 优化LoginCubit的认证状态检查逻辑

修改checkAuthenticationStatus()方法,等待Firebase Auth初始化完成后再获取用户状态,避免同步获取的延迟问题:

Future<void> checkAuthenticationStatus() async {
  emit(LoginLoading());
  // 等待Firebase Auth状态流的第一个值,确保初始化完成
  await FirebaseAuth.instance.authStateChanges().first;
  try {
    var user = _authService.getCurrentUser();
    if (user != null) {
      emit(LoginSuccess(user));
    } else {
      emit(LoginInitial());
    }
  } catch (e) {
    emit(LoginFailure(e.toString()));
  }
}

3. 确认路由与Cubit配置

  • 检查AppRoutes中bottomNavBarRoute和loginRoute的路由名称是否与你的路由配置完全一致。
  • 确保在应用入口处已正确通过BlocProvider提供LoginCubit实例:
BlocProvider(
  create: (context) => LoginCubit(FirebaseAuthService()),
  child: MaterialApp.router(
    routerConfig: yourRouterConfig,
  ),
)

内容的提问来源于stack exchange,提问作者Mahmoud Shaaban

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 22:50:27