An Tran
An Tran

Reputation: 154

How to store a List<Object> to Shared Preferences in Flutter?

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

Upvotes: 0

Views: 273

Answers (2)

nvoigt
nvoigt

Reputation: 77285

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.

Upvotes: 2

HKN
HKN

Reputation: 364

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,
};

Upvotes: 0

Related Questions