I have the following class setup. I was able to store the JSON, but I’m having trouble retrieving it.
import 'package:flutter/material.dart';
class SvItem with ChangeNotifier {
final String id;
final String meatType;
final String meatTypeImg;
final String meatCut;
final String duration;
final String temperatur;
final List<String> instructions;
final String notes;
bool isFavorite;
SvItem({
required this.id,
required this.meatType,
required this.meatTypeImg,
required this.meatCut,
required this.duration,
required this.temperatur,
required this.instructions,
required this.notes,
this.isFavorite = false,
});
factory SvItem.fromJson(Map<String, SvItem> json) {
return SvItem(
id: "id",
meatType: "meatType",
meatTypeImg: "meatTypeImg",
meatCut: "meatCut",
duration: "duration",
temperatur: "temperatur",
instructions: "instructions" as List<String>,
notes: "notes",
isFavorite: "isFavorite" as bool,
);
}
Map<String, dynamic> toJson() {
return {
"id": id,
"meatType": meatType,
"meatTypeImg": meatTypeImg,
"meatCut": meatCut,
"duration": duration,
"temperatur": temperatur,
"instructions": instructions,
"notes": notes,
"isFavorite": isFavorite
};
}
}
With this code, I can save instances of the the custom class in sharedpreferences.
Future saveCustomRecipes(item) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("customRecipesList", jsonEncode(item));
setState(() {});
}
saveCustomRecipes(customRecipes);
But how can I retrieve it and save it in customRecipes?
I tried the following:
getCustomRecipesValues() async {
customRecipes = await getCustomRecipesState();
setState(() {});
}
Future getCustomRecipesState() async {
final prefs = await SharedPreferences.getInstance();
var recipeData = prefs.getString("customRecipesList");
List<SvItem> customRecipes =
SvItem.fromJson(jsonDecode(recipeData!)) as List<SvItem>;
print(customRecipes);
return customRecipes;
}
But I get an error: [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type ‘List’ is not a subtype of type ‘Map<String, dynamic>’
3
Answers
ok I believe I managed to find a solution: This is my SvItem Class:
This is the part to store and retrieve in SP:
And this let's me save to SP and also decode it again:
when you use jsonDecode(recipeData!) it will get a Map not a List.
try convert the code :
into this :
also why did you use jsonEncode not the method toJson from your model class?
You said that you pass a
List<SvItem>
to the function.So you can loop over the list and turn each item into json.
Then you add the json objects to another list and encode it.
Try this:
and