I have a list of RenderModel objects with 2 properties: message and widget. How can i save this list to Shared preferences ? Please tell me the solution. Thank you !
late List<RenderModel> listItems = <RenderModel>[];
CodePudding user response:
You cannot. Widget
is not a class you can just restore. It probably references an existing widget and the next time you run the app, that widget will be gone.
There might be another widget in it's place, but they have no connection. You will need to either save some kind of identifier, to find the widget you referenced, even if the app is closed and reopened, or you have to save some way of reconstructing all those widgets yourself.
CodePudding user response:
You need to convert your list to a json and then store as a String.
you can use something like this to convert the list to string
String renderModelToJson(List<RenderModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
and fromJson and toJson will look like this.
factory RenderModel.fromJson(Map<String, dynamic> json) => RenderModel(
message: json["message"],
widget: json["widget"],
);
Map<String, dynamic> toJson() => {
"message": message,
"widget": widget,
};
CodePudding user response:
Saving Data in Shared Preference
saveData() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
// Encode and store data in SharedPreferences
final String encodedData = RenderModel.encode([
RenderModel(message: 'This is message', widget: 'This is widget'),
]);
await prefs.setString('model_data', encodedData);
// Fetch and decode data
final String? renderModelData = await prefs.getString('model_data');
final List<RenderModel> renderModel = RenderModel.decode(renderModelData!);
print(renderModel[0].message);
}
Your Model Class
class RenderModel{
final String? message;
final String? widget;
String? get getMessage => message;
String? get getWidget => widget;
RenderModel({this.message, this.widget});
factory RenderModel.fromJson(Map<String, dynamic> jsonData) {
return RenderModel(
message: jsonData['message'],
widget: jsonData['widget'],
);
}
static Map<String, dynamic> toMap(RenderModel renderModel) => {
'message': renderModel.message,
'widget': renderModel.widget,
};
static String encode(List<RenderModel> musics) => json.encode(
musics.map<Map<String, dynamic>>((renderModel) => RenderModel.toMap(renderModel)).toList(),
);
static List<RenderModel> decode(String renderModel) =>
(json.decode(renderModel) as List<dynamic>).map<RenderModel>((item) => RenderModel.fromJson(item)).toList();
}