Flutter中SharedPreferences首次启动isLoggedIn默认值异常求助
问题根源
首次启动App时,SharedPreferences中还未存储isLoggedIn键值,调用getBool('isLoggedIn')会返回null。你的判断条件if (sharedPreference.getBool('isLoggedIn') != false)会将null判定为满足条件,因此返回'true',导致错误跳转到已登录页面。
修复方案
1. 修正状态判断逻辑
直接通过??空值运算符设置默认值,仅当isLoggedIn明确为true时才判定为已登录,其余情况(null或false)都视为未登录。同时优化返回值类型为布尔值,避免字符串比较的冗余。
修改后的代码
@override void initState() { super.initState(); verificarToken().then((isLoggedIn) { if (isLoggedIn) { Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const LoginSuccess())); } else { Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => const Login())); } }); } @override Widget build(BuildContext context) { return const Scaffold( body: Center(child: Text('Loading...')), ); } Future<bool> verificarToken() async { SharedPreferences sharedPreference = await SharedPreferences.getInstance(); // 首次启动时getBool返回null,??运算符会取默认值false return sharedPreference.getBool('isLoggedIn') ?? false; }
额外说明
??运算符是Dart中处理空值的简洁方式,当左侧表达式为null时,返回右侧的默认值。- 将返回值从字符串改为布尔值,代码更直观,也避免了字符串匹配可能带来的潜在错误。
内容的提问来源于stack exchange,提问作者Rafael Reis
相关产品推荐
相关产品推荐

