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

Flutter中SharedPreferences的then回调未触发,控制台无wow输出的原因

问题原因及解决方法

你的代码里SharedPreferences.getInstance().then的回调没触发,核心问题是回调写法错误:

你写的是:

SharedPreferences.getInstance().then((prefs) => () { ... })

这里的=> () { ... }相当于返回了一个未被执行的匿名函数,而不是直接执行回调逻辑——then拿到这个返回的函数后并不会调用它,所以里面的print("wow")自然不会输出。

修正方法

直接去掉外层的箭头函数和多余的函数包装,两种方式都可以:

方式1:使用大括号直接写回调逻辑

SharedPreferences.getInstance().then((prefs) {
  print("wow");
  String? token = prefs.getString('apitoken');

  print("the auth key is " + token.toString());

  key = hmacSha
    .convert(utf8.encode(hashValue + token.toString()))
    .toString();
});

方式2:箭头函数写法(仅适用于单行逻辑,多行推荐方式1)

如果逻辑是单行代码,可以直接用=>写逻辑,不要套额外的函数:

// 示例:单行逻辑的写法
SharedPreferences.getInstance().then((prefs) => print(prefs.getString('apitoken')));

简单说就是:then需要的是直接执行逻辑的函数,而不是返回另一个函数的函数,你的写法相当于给了then一个“函数生成器”,而非实际要执行的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:57:13