Home > Software engineering >  How to save a list of objects locally in Flutter?
How to save a list of objects locally in Flutter?

Time:10-06

I have a page from which I need to save data locally as a list. To save, I use SharedPrefs, there, through the model, I save the data as a list. But I ran into a problem that I can not specify the format for receiving data List, tell me how can I save data as a list and receive data as a list?

class RecentlySearchedModel {
  String name;
  String address;

  RecentlySearchedModel({
    required this.name,
    required this.address,
  });

  factory RecentlySearchedModel.fromJson(Map<String, dynamic> json) {
    return RecentlySearchedModel(
      name: json['name'] as String,
      address: json['address'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'address': address,
    };
  }
}

repository

 @override 
  Future setResentlySearched({required List<RecentlySearchedModel> searchedList}) async {
    final SharedPrefs prefs = SharedPrefs();
    await prefs.setString(_name, jsonEncode( ))
  }

  @override 
  Future<List<RecentlySearchedModel>?> getResentlySearched() async {
    final SharedPrefs prefs = SharedPrefs();
    final data = await prefs.getString(_name);

    if (data == null) return null;

    return List<RecentlySearchedModel>.fromJson(
      jsonDecode(data),
    );
  }

CodePudding user response:

update your repository like this.

 @override 
  Future setResentlySearched({required List<RecentlySearchedModel> searchedList}) async {
    final SharedPrefs prefs = SharedPrefs();
    await prefs.setString(_name, jsonEncode(searchedList.toJson());
  }

  @override 
  Future<List<RecentlySearchedModel>?> getResentlySearched() async {
    final SharedPrefs prefs = SharedPrefs();
    final data = await prefs.getString(_name);


    if (data == null) return null;
    Iterable l = json.decode(data);
    List<RecentlySearchedModel> posts = List<RecentlySearchedModel>.from(l.map((model)=> RecentlySearchedModel.fromJson(model)));    
   return posts;
  }

CodePudding user response:

i havent try to complie, but its should be like this

Future setResentlySearched({required List<RecentlySearchedModel> searchedList}) async {

    List<Map<String,dynamic>> listItem = searchedList.map((e)=> e.toJson()).toList();

    String jsonString = jsonEncode(listItem);
    final SharedPrefs prefs = SharedPrefs();
    await prefs.setString(_name, jsonString)
  }

and get it back

 Future<List<RecentlySearchedModel>?> getResentlySearched() async {
    final SharedPrefs prefs = SharedPrefs();
    final data = await prefs.getString(_name);

    if (data == null) return null;
    return (jsonDecode(data) as List).map((e)=> RecentlySearchedModel.fromJson(e)).toList();
   
  }
  • Related