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

iOS端使用shared_preferences保存字符串时抛出异常

iOS端使用shared_preferences保存字符串报错的解决方案

问题现象

  • 登录代码中调用prefs.setString('username', username)在Android模拟器及真机运行正常,但iOS端(iPhone 14 Pro Max)抛出以下异常:

    [VERBOSE-2: dart_vm_initializer.cc(41)] Unhandled Exception: type Map<Object?, Object?>' is not a subtype of type 'List<Object?>?' in type cast
    #0 UserDefaultsApi.setValue (package:shared_preferences_foundation/messages.g.dart:95:59)

    #1 SharedPreferencesFoundation.setValue (package:shared_preferences_foundation/shared_preferences_foundation.dart:77:5)

    #2 UserProvider.login (package:vks_flutter_app/providers/user_provider.dart:32:5)

  • 使用版本:shared_preferences: ^2.1.1、XCode 14、Flutter 3.7.12

解决方案

  • 升级shared_preferences依赖版本
    该版本的iOS端实现(shared_preferences_foundation)存在已知类型转换bug,升级到>=2.2.0的稳定版本可修复问题。修改pubspec.yaml中的依赖:

    shared_preferences: ^2.2.0 # 或更高官方稳定版本
    

    执行flutter pub get更新依赖后重新构建项目。

  • 清理iOS构建缓存
    若升级后问题仍存在,清理缓存确保新依赖生效:

    1. 执行flutter clean
    2. 删除iOS目录下的Pods文件夹和Podfile.lock:
      rm -rf ios/Pods
      rm ios/Podfile.lock
      
    3. 进入iOS目录执行pod install
    4. 重新运行项目:flutter run
  • 排查其他代码干扰
    临时注释项目中其他SharedPreferences相关操作,仅保留setString测试,确认是否是其他代码(如错误存储Map类型数据)或插件冲突导致的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:00:19