Flutter中如何序列化枚举列表并存储到SharedPreferences?
你遇到的错误是因为Dart默认的json.encode无法识别带有@JsonEnum和@JsonValue注解的枚举实例——这些注解是给json_serializable库用的,默认编码器不知道如何将枚举转换为可编码的JSON值。以下是两种可行的解决方案:
方案一:使用json_serializable生成序列化代码
这是长期维护项目的规范方式:
- 确保
pubspec.yaml依赖配置正确:
dependencies: json_annotation: ^4.8.1 dev_dependencies: build_runner: ^2.4.4 json_serializable: ^6.7.1
- 运行代码生成命令:
flutter pub run build_runner build
运行后会自动生成枚举的序列化/反序列化代码,每个枚举值将拥有toJson()和fromJson()方法。
- 序列化存储枚举列表:
final preferences = await SharedPreferences.getInstance(); // 将每个枚举转换为对应的JSON值,再编码为字符串 final encodedList = stepState.map((state) => state.toJson()).toList(); await preferences.setString('stepState', json.encode(encodedList));
- 反序列化读取:
final preferences = await SharedPreferences.getInstance(); final storedString = preferences.getString('stepState'); if (storedString != null) { final decodedList = json.decode(storedString) as List<String>; final restoredStepState = decodedList.map((s) => MyStepState.fromJson(s)).toList(); }
方案二:手动实现枚举与字符串的转换
如果不想依赖json_serializable,可以给枚举写扩展方法手动处理:
- 添加枚举扩展:
extension MyStepStateConverter on MyStepState { // 将枚举转换为对应的JSON字符串值 String toJsonString() { switch (this) { case MyStepState.indexed: return 'indexed'; case MyStepState.editing: return 'editing'; case MyStepState.complete: return 'complete'; case MyStepState.disabled: return 'disabled'; case MyStepState.error: return 'error'; } } // 从JSON字符串值转换回枚举 static MyStepState fromJsonString(String value) { switch (value) { case 'indexed': return MyStepState.indexed; case 'editing': return MyStepState.editing; case 'complete': return MyStepState.complete; case 'disabled': return MyStepState.disabled; case 'error': return MyStepState.error; default: throw ArgumentError('无效的MyStepState值: $value'); } } }
- 存储枚举列表:
final preferences = await SharedPreferences.getInstance(); final encodedList = stepState.map((state) => state.toJsonString()).toList(); await preferences.setString('stepState', json.encode(encodedList));
- 读取并反序列化:
final preferences = await SharedPreferences.getInstance(); final storedString = preferences.getString('stepState'); if (storedString != null) { final decodedList = json.decode(storedString) as List<String>; final restoredStepState = decodedList.map(MyStepStateConverter.fromJsonString).toList(); }
内容的提问来源于stack exchange,提问作者HelpWanted
相关产品推荐
相关产品推荐

