Search code examples
flutterdartsharedpreferences

Store list of a particular type to shared preference


I've my list, which I'm getting from the json. So, I want to pass that list through shared preference. But, when I try to use setStringList of shared preference, I'm facing an exception.

type 'List<ApprovalStatus>' is not a subtype of type 'List<String>'

And ApprovalStatus is a class, which is defined as:

class ApprovalStatus {
  final items;
  final index;
  final approvalStatus;

  ApprovalStatus({this.items, this.index, this.approvalStatus});

  @override
  String toString() {
    return "${this.approvalStatus}";
  }
}

Can't we use user defined type List to shared preference/ If not, the how can we store the user defined type list using shared preference?


Solution

  • The error suggests that you are trying to pass List of ApprovalStatus directly to be saved in shared prefs. It expects a List of String.

    Try this:

    prefs.setStringList(approvalList.map((m) => m.toString()).toList());

    Make sure to put some serialization logic in toString so that you can retrieve the data back.

    Alternatively, you can directly save the JSON array as a string property in shared prefs.