Flutter:如何转换列表数据类型适配SharedPreferences的SetStringList方法?
核心思路
SharedPreferences仅支持存储字符串列表,因此需要将自定义对象序列化为JSON字符串后存入,读取时再反序列化为原对象,以此解决类型不匹配问题。
步骤1:给自定义对象添加序列化/反序列化方法
假设你的自定义对象是Busqueda,先给它添加转JSON字符串和从JSON字符串还原的方法:
class Busqueda { final String name; // 可添加其他属性,如搜索时间、ID等 Busqueda({required this.name}); // 将对象转为JSON字符串 String toJson() { return jsonEncode({'name': name}); // 有其他属性时,同步添加到Map中 } // 从JSON字符串还原为对象 static Busqueda fromJson(String jsonStr) { final Map<String, dynamic> data = jsonDecode(jsonStr); return Busqueda(name: data['name']); } }
步骤2:修改存储逻辑(解决onPressed中的类型错误)
在点击存储的onPressed方法中,先把自定义对象列表转成字符串列表,再调用setStringList:
onPressed: () async { final prefs = await SharedPreferences.getInstance(); // 将对象列表映射为JSON字符串列表 final List<String> historialStrings = historialMenuPrincipal .map((busqueda) => busqueda.toJson()) .toList(); // 存储字符串列表 await prefs.setStringList('historial_menu_principal', historialStrings); },
步骤3:读取并还原对象列表
从SharedPreferences读取字符串列表后,再转换回自定义对象列表:
Future<List<Busqueda>> loadHistorial() async { final prefs = await SharedPreferences.getInstance(); final List<String>? historialStrings = prefs.getStringList('historial_menu_principal'); if (historialStrings == null) return []; // 将字符串列表还原为对象列表 return historialStrings.map((str) => Busqueda.fromJson(str)).toList(); }
步骤4:展示对象属性
读取完成后即可正常访问对象属性:
// 示例:在控制台打印第一条历史记录的name loadHistorial().then((historial) { if (historial.isNotEmpty) { print(historial[0].name); } }); // 示例:在Text组件中展示所有历史记录 FutureBuilder<List<Busqueda>>( future: loadHistorial(), builder: (context, snapshot) { if (snapshot.hasData) { return Column( children: snapshot.data!.map((busqueda) { return Text(busqueda.name); }).toList(), ); } return const CircularProgressIndicator(); }, )
内容的提问来源于stack exchange,提问作者Anes
相关产品推荐
相关产品推荐

