0

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>[];

enter image description here

An Tran
  • 119
  • 9
  • check this answer https://stackoverflow.com/questions/61316208/how-to-save-listobject-to-sharedpreferences-in-flutter – Sabahat Hussain Qureshi Aug 01 '22 at 09:43
  • I have tried to do like that. But i had a error at the encode method. "Exception has occurred. JsonUnsupportedObjectError (Converting object to an encodable object failed: Instance of Row" – An Tran Aug 01 '22 at 09:48

2 Answers2

2

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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
0

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,
};
HKN
  • 264
  • 1
  • 8