Im trying to convert a json string to a list of objects in my flutter project. When I try to do that I get this error
Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method 'map'.
My Object looks like this
class UpdateItem {
final String? title;
final bool? selected;
UpdateItem({this.title, this.selected});
factory UpdateItem.fromJson(dynamic json) {
return UpdateItem(
title: json['title'] as String,
selected: json['selected'] as bool,
);
}
@override
String toString() {
return '{ ${this.title}, ${this.selected} }';
}
Map toJson() => {
'title': title,
'selected': selected,
};
}
where I set list of objects to json and save that in shared preferences.
Future<String?> getSelectedList(String k) async =>
preferenceHelper.getStringPrefs(k);
setSelectedList(String k, dynamic d) async =>
preferenceHelper.updateJsonPrefs(k, d);
updateStringPrefs(String key, String value) async {
prefs = await SharedPreferences.getInstance();
prefs.setString(key, value);
}
Future<String?> getStringPrefs(String key) async {
prefs = await SharedPreferences.getInstance();
return prefs.getString(key) ?? "";
}
Future<void> saveSelectedList(List<UpdateItem> list) async {
var title = _categoryModelList![pageNo].title;
String encodedData = json.encode(list);
DataManager _dataManager = new DataManager();
_dataManager.setSelectedList(title!, encodedData);
//
_updateItemProvider!.removeAll();
}
Where I try to get that saved json string and convert it to a List of objects.
for (var i = 0; i < _categoryModelList!.length; i++) {
String s = _categoryModelList![i].title!;
var t = await _dataManager.getSelectedList(s);
var updateObj = json.decode(t!);
// error referee here.......
List<UpdateItem> list =
updateObj.map((e) => UpdateItem.fromJson(e)).toList();
print(list);
}
Where and what i'm doing wrong here. Can anyone help me out with this please? Here is the json response I get
\"[{\\"title\\":\\"Hearing Loops\\",\\"selected\\":true},{\\"title\\":\\"Hearing Assistance\\",\\"selected\\":true}]\"