Home > OS >  How to save list data in SharedPreferences flutter
How to save list data in SharedPreferences flutter

Time:07-30

I make data connection with database to bring a list of data such as the following code:


  var listDATA = [];
  Future listDATAs() async {
    api = '*************';
    var response = await http.post(Uri.parse(api));

    var responsebody = jsonDecode(response.body);

    if (responsebody.length >0){

      for (int i = 0; i < responsebody.length; i  ) {
        listDATA.add(responsebody[i]['name']  ':'   responsebody[i]['image'].toString());

      }

      return responsebody;
    }else{


    }
  }

How can I store listDATA in Shared Preferences I need to save name and image ? Then recall it to display after storage

CodePudding user response:

It's preferred not to store non-primitive data types in SharedPreferences as it supports only primitive data types by default. But still there is a way to do it.

you can store the response body of your API call without decoding JSON to a String value.

// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();
// Save an String value to 'response' key.
await prefs.setString('response', response.body);

if you have response types of List, you can use setStringList method

await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);

CodePudding user response:

in this way you can store list value in shared preference

static setListValue(String key, List< ProductsModel > value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(key, jsonEncode(value.map((e) => e.toJson()).toList()));
}

her I make a standard method to store list values from any class by calling

setListValue('store_list', listData);

after that, you have to make a method for getting this list value

//getListValue
static Future<List<ProductsModel>?> getListValue(String key) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final dataMap = jsonDecode(prefs.getString(key) ?? '[]') as 
List<dynamic>;

return dataMap.map<ProductsModel>((item) {
  return ProductsModel.fromJson(item);
}).toList();
}

after that, you can call this method like this

var listValue = await SPUtils.getListValue('store_list');

CodePudding user response:

// for saving the list in shared preferences

final prefs = await SharedPreferences.getInstance(); prefs.setString("list",jsonEncode(listDATA));

// for getting the list from shared preferences

final prefs = await SharedPreferences.getInstance();

List listDATA = jsonDecode(prefs.get("list"));

CodePudding user response:

You can follow those steps.

  1. convert your object to map with toMap() method.
  2. encode your map to string with encode() method.
    Save the string to shared preferences.

final SharedPreferences prefs = await SharedPreferences.getInstance();

await prefs.setString('key', encodedData);

// Fetch and decode data

final String musicsString = await prefs.getString('musics_key');

Example :

import 'dart:convert';

void main() async {  
 final SharedPreferences prefs = await SharedPreferences.getInstance();

final String encodedData = Music.encode([ Music(id: 1, ...), Music(id: 2, ...), Music(id: 3, ...), ]);

  await prefs.setString('musics_key', encodedData);

  // Fetch and decode data   final String musicsString = await prefs.getString('musics_key');

  final List<Music> musics = Music.decode(musicsString); }

class Music {  

final int id;
final String name, size, rating, duration, img; bool favorite;

  Music({
    this.id,
    this.rating,
    this.size,
    this.duration,
    this.name,
    this.img,
    this.favorite,   });

  factory Music.fromJson(Map<String, dynamic> jsonData) {
    return Music(
      id: jsonData['id'],
      rating: jsonData['rating'],
      size: jsonData['size'],
      duration: jsonData['duration'],
      name: jsonData['name'],
      img: jsonData['img'],
      favorite: false,
    );   }

  static Map<String, dynamic> toMap(Music music) => {
        'id': music.id,
        'rating': music.rating,
        'size': music.size,
        'duration': music.duration,
        'name': music.name,
        'img': music.img,
        'favorite': music.favorite,
      };

  static String encode(List<Music> musics) => json.encode(
        musics
            .map<Map<String, dynamic>>((music) => Music.toMap(music))
            .toList(),
      );

  static List<Music> decode(String musics) =>
      (json.decode(musics) as List<dynamic>)
          .map<Music>((item) => Music.fromJson(item))
          .toList(); }
  • Related