如何获取Map中SearchDelegateModel实例的具体属性值?
解决方法
问题出在你存储的是SearchDelegateModel实例的默认toString()结果——这个方法只会返回Instance of 'SearchDelegateModel',不包含任何属性数据,所以读取后自然拿不到具体属性。要正确存储和读取模型数据,需要把对象序列化为JSON字符串,步骤如下:
1. 给模型类添加序列化方法
修改SearchDelegateModel,增加toJson方法,用来把实例转成可序列化的Map:
class SearchDelegateModel { String apodo; String name; SearchDelegateModel({this.apodo, this.name}); factory SearchDelegateModel.fromJson(Map<String, dynamic> parsedJson) { return SearchDelegateModel( name: parsedJson['name'], apodo: parsedJson['apodo'], ); } // 新增:将实例转为Map Map<String, dynamic> toJson() { return { 'apodo': apodo, 'name': name, }; } }
2. 修改存储与读取逻辑
把模型转成JSON字符串后再存入SharedPreferences,读取时再把JSON字符串转回模型实例,这样就能直接访问属性了:
IconButton( icon: Icon(Icons.search), onPressed: () async { SharedPreferences prefs = await SharedPreferences.getInstance(); final busqueda = await showSearch(context: context, delegate: SearchDelegateMenuPrincipal("Buscar...", this.historialMenuPrincipal)); if (busqueda != null) { historialMenuPrincipal.removeWhere((item) => item.apodo == busqueda.apodo); this.historialMenuPrincipal.insert(0, busqueda); // 把每个模型转成JSON字符串,存入StringList final historialJsonList = historialMenuPrincipal .map((model) => json.encode(model.toJson())) .toList(); prefs.setStringList("HistorialBusquedaPreferences", historialJsonList); // 读取并解析回模型实例 var storedList = prefs.getStringList("HistorialBusquedaPreferences"); if (storedList != null) { List<SearchDelegateModel> parsedModels = storedList .map((jsonStr) => SearchDelegateModel.fromJson(json.decode(jsonStr))) .toList(); // 直接访问模型属性 parsedModels.forEach((model) { print("apodo: ${model.apodo}, name: ${model.name}"); }); } } }, ),
关键说明
- 不要依赖对象的默认
toString()方法存储数据,它只是实例的标识,不包含业务数据 - 通过JSON序列化/反序列化,可以完整保存和恢复模型的属性信息
内容的提问来源于stack exchange,提问作者Anes
相关产品推荐
相关产品推荐

