0

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

4 Answers 4

1

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']);
Sign up to request clarification or add additional context in comments.

5 Comments

Hi bro / I make it like that / var responsebody = jsonDecode(response.body); final prefs = await SharedPreferences.getInstance(); await prefs.setString('response', responsebody); var myData = prefs.getString('response'); String token = jsonDecode(myData!); print(token); / and I get this error / [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'
Please make sure to not decode response. It means you must not use jsonDecode before storing the values.
Hello brother / yes that works fine but now if I want to use this list that I have stored like this and show it for example in the listview can I do that? I apologize but I am not a professional
You can get that list from SharedPreference and then use jsonDecode then it will be converted to List<dynamic>
Thank you brother, I will try it and if I don't succeed, I will ask a new question
1

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');

Comments

1

// 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"));

Comments

1

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(); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.