Flutter应用卡在splash screen无法跳转至登录页或主页的问题
- 导航卡死的直接诱因是上下文使用错误
- 隐藏逻辑bug是变量作用域遮蔽
- 配置错误是路由参数拼写失误
上下文错误细节
你在_MyAppState中直接调用Navigator.pushReplacementNamed时,传入的context属于MaterialApp外层的组件。MaterialApp内部才会初始化全局Navigator实例,只有位于Navigator子树内的组件context才能正常调用导航方法,用外层context调用就会触发Navigator operation requested with a context that does not include a Navigator的异常,导航动作直接中断,导致Splash页卡死。
变量遮蔽问题细节
你在文件顶层定义了全局变量bool authSignedIn,但在getUser()方法内部写了bool authSignedIn = prefs.getBool('auth') ?? false,这行代码会创建一个和全局变量同名的局部变量,全局的authSignedIn始终没有被赋值,一直保持初始值null,导致你编写的登录状态判断逻辑永远偏离预期。
另外原判断条件authSignedIn != false存在漏洞:当authSignedIn为初始值null时,null != false的判断结果为true,会导致未登录用户被错误引导到已登录页面。
路由配置错误细节
代码中写的initial route:'/'存在空格,和MaterialApp的路由参数名initialRoute不匹配,会导致路由初始化不生效。
1. 拆分独立Splash页面
把原本写在MyApp里的Scaffold内容抽成独立的SplashScreen组件,所有导航逻辑都放在这个组件的State内执行——这个组件作为MaterialApp路由树的一部分,它的context天然处于Navigator子树内,可以正常执行导航操作。
2. 修正变量赋值逻辑
在getUser()方法中,给authSignedIn赋值时去掉类型声明,直接修改全局变量,避免局部同名变量遮蔽全局值;同时将登录判断条件优化为authSignedIn == true,消除空值判断的逻辑漏洞。
3. 修正路由参数拼写
把错误的initial route改为initialRoute,将独立Splash页面注册为根路由。
void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Login', initialRoute: '/', routes: { '/': (context) => SplashScreen(), '/toprofilepage': (context) => FirstScreen(), '/tologinpage': (context) => LoginPage(), }, ); } } class SplashScreen extends StatefulWidget { @override _SplashScreenState createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> { @override void initState() { super.initState(); getUserInfo(); } Future getUserInfo() async { await getUser(); navigateUser(); } void navigateUser() { final targetRoute = (uid != null && authSignedIn == true) ? '/toprofilepage' : '/tologinpage'; Timer(const Duration(seconds: 2), () { Navigator.pushReplacementNamed(context, targetRoute); }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text( "Saraswat", style: TextStyle( fontSize: 40, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic ), ), ), ); } }
对应getUser()方法的修正部分:
Future getUser() async { await Firebase.initializeApp(); SharedPreferences prefs = await SharedPreferences.getInstance(); // 去掉bool类型声明,直接给全局authSignedIn赋值 authSignedIn = prefs.getBool('auth') ?? false; final User? user = _auth.currentUser; if (authSignedIn == true && user != null) { uid = user.uid; name = user.displayName; imageUrl = user.photoURL; } }
内容的提问来源于stack exchange,提问作者Serex App

