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

Flutter中SharedPreferences首次启动isLoggedIn默认值异常求助

解决SharedPreferences首次启动默认登录状态错误问题

问题根源

首次启动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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:43:29