Home > Software design >  Flutter & Shared Preferences: How do i save and read back a List<Object> using setStringList?
Flutter & Shared Preferences: How do i save and read back a List<Object> using setStringList?

Time:02-09

class Restaurant {
  Restaurant({
    required this.name,
    required this.description,
    required this.address,
    required this.imageUrl,
  });

  Restaurant.fromJson(Map<String, Object?> json)
      : this(
          name: json['name']! as String,
          description: json['description']! as String,
          address: json['address']! as String,
          imageUrl: json['imageUrl'] as String,
        );

  final String name;
  final String description;
  final String address;
  final String imageUrl;

  Map<String, Object?> toJson() {
    return {
      'name': name,
      'description': description,
      'address': address,
      'imageUrl': imageUrl,
    };
  }
}

I get the list of restaurants from Firebase and when the user clicks Favorite Icon, I want to save that restaurant locally and retrieve the list of favorite restaurants and show it on another page. I know I can do it on Firebase directly but for now, I want it saved locally.

I am looking forward to hearing from all of you. Thank you.

CodePudding user response:

Like this

List<Restaurant> restaturants = [Restuarant(...),Restuarant(...)];
List<String> encodedRestaturants = restaturants.map((res)=>json.encode(res.toJson())).toList();

//to write
prefs.setStringList("restaturants",encodedRestaturants);

//to read
List<String> decodedRestaturantsString = prefs.getStringList("restaturants");
List<Restaurant> decodedRestaturants = decodedRestaturantsString.map((res)=>Restaturant.fromJson(json.decode(res))).toList();

CodePudding user response:

Instead using SharedPreferences setStringList, you can use setString.

Here excerpt using setStringList:

 // sample restaurants.
 List<Restaurant> favoriteRestos = [resto1, resto2, resto3];

 List<String> favorites = [];

 // Generate json for each restaurant
 for(var resto in favoriteRestos) {
    var json = jsonEncode(resto);
    favorites.add(json);
 }

// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();

// saving
await prefs.setStringList('favorites', favorites);

// Reading part
List<String> jsonRestos = prefs.getStringList('favorites')??[];

List<Restaurant> resFavorites = [];
for(var jsonResto in jsonRestos) {
   var map = jsonDecode(jsonResto);
   var resto = Restaurant.fromJson(map);
   resFavorites.add(resto);
}

For setString:

List<Restaurant> favoriteRestos = [resto1, resto2, resto3];
var json = jsonEncode(favoriteRestos);

// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();

// saving
await prefs.setString('favorites', json);

// reading
var resJson = prefs.getString('favorites')??'';
var parsedJson = jsonDecode(resJson);
List<Restaurant> items = List<Restaurant>.from(parsedJson.map((i) => Restaurant.fromJson(i)));

Note: You need to update your Restaurant class. See https://docs.flutter.dev/development/data-and-backend/json#serializing-json-inside-model-classes

  •  Tags:  
  • Related