简体   繁体   English

如何在 Flutter 的 SharedPreferences 中保存列表

[英]How to Save List in SharedPreferences in Flutter

Hello all at first I want to mention that I've tried a lot of solutions here but it didn't work for me.大家好,首先我想提一下,我在这里尝试了很多解决方案,但对我没有用。

I bring the list from the database through the following code:我通过以下代码从数据库中获取列表:

 var listCat = [];
  Future getdata() async {
    apiURL = '***************.php';
    var response = await http.post(Uri.parse(apiURL));
    var responsebody = jsonDecode(response.body);
    if (responsebody.length >0){
      for (int i = 0; i < responsebody.length; i++) {
        listCat.add(responsebody[i]['name']+ ':' + responsebody[i]['image'].toString());
      }
      return responsebody;
    }else{
  

    }
  }

As is obvious in the code above I am trying to get the name and image and this is not a problem right now I want to store this listCat in SharedPreferences until I recall it from all pages of the app在上面的代码中很明显,我正在尝试获取名称和图像,现在这不是问题我想将此 listCat 存储在 SharedPreferences 中,直到我从应用程序的所有页面中调用它

I have the following class to save SharedPreferences:我有以下 class 来保存 SharedPreferences:

class APIPreferences {
  static SharedPreferences ? _preferences;
  static const _keyMuinCat = 'MuinCat';



  static Future init() async => _preferences = await SharedPreferences.getInstance();


  static Future setMuinCat(String MuinCat) async => await _preferences!.setString(_keyMuinCat, MuinCat);



  static String? getMuinCat() => _preferences!.getString(_keyMuinCat);



}

Then I save what I need to save by the following line:然后我通过以下行保存我需要保存的内容:

APIPreferences.setMuinCat(listCat.toString());

Then I can bring pre-stored data from any location where I need it through the following code:然后我可以通过以下代码从我需要的任何位置获取预存储的数据:

CatList = APIPreferences.getMuinCat() ?? '';

I tried to do the following thing now to save the list in the first code above:我现在尝试执行以下操作以将列表保存在上面的第一个代码中:

var listCat = [];
  Future getdata() async {
    apiURL = '***************.php';
    var response = await http.post(Uri.parse(apiURL));

    var responsebody = jsonDecode(response.body);

    if (responsebody.length >0){

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

      }

      return responsebody;
    }else{


    }
  }

But it didn't work.但它没有用。 I don't really know how to deal with it.我真的不知道如何处理它。

How can I save it and then bring it to use with ListView.如何保存它然后将其与 ListView 一起使用。

To save the list in shared preferences you need to pass as jsonEncode(yourList data) and when you will fecth the shared list you will again jsonDecode(your list)要将列表保存在共享首选项中,您需要作为 jsonEncode(yourList data) 传递,并且当您对共享列表进行验证时,您将再次 jsonDecode(your list)

await prefs.setString('YOUR KEY', json.encode(YOURMAP()));

instead of:代替:

_preferences!.setString(_keyMuinCat, "some string");

use:利用:

_preferences!.setStringList(_keyMuinCat, ["some", "strings", "in", "list"]);

So in your code, the setMuinCat method needs to be:因此,在您的代码中, setMuinCat方法必须是:

static Future setMuinCat(List<String> muinCat) async => await _preferences!.setStringList(_keyMuinCat, muinCat);

and then you call it like this:然后你这样称呼它:

APIPreferences.setMuinCat((listCat as List).map((v) => v.toString()).toList());

如何保存列表<object>到 Flutter 中的 SharedPreferences?<div id="text_translate"><p> 我有一个最喜欢的音乐列表,我在第一次打开应用程序时从音乐中检索,该应用程序从收藏夹中获取最喜欢的音乐列表。 我想将此列表保存到共享</p><pre>preferences.List&lt;Music&gt; favoriteMusic = new List&lt;Music&gt;();</pre><p> 其中音乐 class 是:</p><pre> 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&lt;String, dynamic&gt; jsonData){ return Music( id: jsonData['id'], rating: jsonData['rating'], size: jsonData['size'], duration: jsonData['duration'], name: jsonData['name'], img: jsonData['img'], favorite: false, ); } }</pre><p> 如何保存最喜欢的音乐列表?</p></div></object> - How to save List<Object> to SharedPreferences in Flutter?

Flutter 如何保存和显示列表<object>共享首选项?<div id="text_translate"><p> 我想保存并阅读一个名为 coursefav 的元素列表。</p><p> 我有以下代码,我在其中制作了 class 的 map,但我不知道如何保存字符串 map 的元素,然后在列表中一个一个地显示,然后在列表视图中显示所有元素。</p><p> 这就是我所拥有的</p><pre>//my class class curso { final String title; final String entidad; final String categoria; final String emision; final String imgcourse; final String urlcourse; final String idioma; final String duracion; final String description; curso({ required this.title, required this.entidad, required this.categoria, required this.emision, required this.imgcourse, required this.urlcourse, required this.idioma, required this.duracion, required this.description, }); Map&lt;String, dynamic&gt; toMap() { return { 'title': title, 'entidad': entidad, 'categoria': categoria, 'emision': emision, 'imgcourse': imgcourse, 'urlcourse': urlcourse, 'idioma': idioma, 'duracion': duracion, 'description': description, }; } curso.fromMap(Map&lt;String, dynamic&gt; res): title = res["title"], entidad = res["entidad"], categoria = res["categoria"], emision = res["emision"], imgcourse = res["imgcourse"], urlcourse = res["urlcourse"], idioma = res["idioma"], duracion = res["duracion"], description = res["description"]; @override String toString() { return 'curso{title: $title, entidad: $entidad, categoria: $categoria, emision: $emision, imgcourse: $imgcourse, urlcourse: $urlcourse, idioma: $idioma, duracion: $duracion, description: $description}'; } }</pre><p> 我就是这样称呼的</p><pre> void saveCourseFavSP(String title,String entidad,String categoria,String emision,String imgcourse,String urlcourse,String idioma,String duracion,String description) async { //init sharedpreferences SharedPreferences cursosFav = await SharedPreferences.getInstance(); //object variable to load the info final testCursoFav = curso( title: title, entidad: entidad, categoria: categoria, emision: emision, imgcourse: imgcourse, urlcourse: urlcourse, idioma: idioma, duracion: duracion, description: description); String json = jsonEncode(testCursoFav); print("generating json $json"); //sending all items object to sharedPreferences cursosFav.setString('coursesFavorites', json); //here i want to insert String to List&lt;Strin&gt; //sending String to something like.upperCase //but i dont know how to parse and how to read List&lt;String&gt; lista = jsonDecode(json); } loadDataCursosFavSP() async { SharedPreferences cursosFav = await SharedPreferences.getInstance(); String? json = cursosFav.getString("coursesFavorites"); print("datos de curso favorito cargados:\n $json"); if (json == null) { print("Items doesn't exist"); } else { Map&lt;String, dynamic&gt; map = jsonDecode(json); final cursofav = curso.fromMap(map); print( "titulo fav: ${cursofav.title}, ${cursofav.entidad},${cursofav.emision},"); } } clearDataCursosFavSP() async { SharedPreferences cursosFav = await SharedPreferences.getInstance(); cursosFav.clear(); print("ALL ITEMS LIST ARE DELETED"); }</pre></div></object> - Flutter How to save and show List<Object> to SharedPreferences?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何保存列表<list<string> &gt; 在 Flutter 中使用 SharedPreferences </list<string> - How to save List<List<String>> with SharedPreferences in Flutter 如何保存列表<object>到 Flutter 中的 SharedPreferences?<div id="text_translate"><p> 我有一个最喜欢的音乐列表,我在第一次打开应用程序时从音乐中检索,该应用程序从收藏夹中获取最喜欢的音乐列表。 我想将此列表保存到共享</p><pre>preferences.List&lt;Music&gt; favoriteMusic = new List&lt;Music&gt;();</pre><p> 其中音乐 class 是:</p><pre> 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&lt;String, dynamic&gt; jsonData){ return Music( id: jsonData['id'], rating: jsonData['rating'], size: jsonData['size'], duration: jsonData['duration'], name: jsonData['name'], img: jsonData['img'], favorite: false, ); } }</pre><p> 如何保存最喜欢的音乐列表?</p></div></object> - How to save List<Object> to SharedPreferences in Flutter? Flutter 如何保存和显示列表<object>共享首选项?<div id="text_translate"><p> 我想保存并阅读一个名为 coursefav 的元素列表。</p><p> 我有以下代码,我在其中制作了 class 的 map,但我不知道如何保存字符串 map 的元素,然后在列表中一个一个地显示,然后在列表视图中显示所有元素。</p><p> 这就是我所拥有的</p><pre>//my class class curso { final String title; final String entidad; final String categoria; final String emision; final String imgcourse; final String urlcourse; final String idioma; final String duracion; final String description; curso({ required this.title, required this.entidad, required this.categoria, required this.emision, required this.imgcourse, required this.urlcourse, required this.idioma, required this.duracion, required this.description, }); Map&lt;String, dynamic&gt; toMap() { return { 'title': title, 'entidad': entidad, 'categoria': categoria, 'emision': emision, 'imgcourse': imgcourse, 'urlcourse': urlcourse, 'idioma': idioma, 'duracion': duracion, 'description': description, }; } curso.fromMap(Map&lt;String, dynamic&gt; res): title = res["title"], entidad = res["entidad"], categoria = res["categoria"], emision = res["emision"], imgcourse = res["imgcourse"], urlcourse = res["urlcourse"], idioma = res["idioma"], duracion = res["duracion"], description = res["description"]; @override String toString() { return 'curso{title: $title, entidad: $entidad, categoria: $categoria, emision: $emision, imgcourse: $imgcourse, urlcourse: $urlcourse, idioma: $idioma, duracion: $duracion, description: $description}'; } }</pre><p> 我就是这样称呼的</p><pre> void saveCourseFavSP(String title,String entidad,String categoria,String emision,String imgcourse,String urlcourse,String idioma,String duracion,String description) async { //init sharedpreferences SharedPreferences cursosFav = await SharedPreferences.getInstance(); //object variable to load the info final testCursoFav = curso( title: title, entidad: entidad, categoria: categoria, emision: emision, imgcourse: imgcourse, urlcourse: urlcourse, idioma: idioma, duracion: duracion, description: description); String json = jsonEncode(testCursoFav); print("generating json $json"); //sending all items object to sharedPreferences cursosFav.setString('coursesFavorites', json); //here i want to insert String to List&lt;Strin&gt; //sending String to something like.upperCase //but i dont know how to parse and how to read List&lt;String&gt; lista = jsonDecode(json); } loadDataCursosFavSP() async { SharedPreferences cursosFav = await SharedPreferences.getInstance(); String? json = cursosFav.getString("coursesFavorites"); print("datos de curso favorito cargados:\n $json"); if (json == null) { print("Items doesn't exist"); } else { Map&lt;String, dynamic&gt; map = jsonDecode(json); final cursofav = curso.fromMap(map); print( "titulo fav: ${cursofav.title}, ${cursofav.entidad},${cursofav.emision},"); } } clearDataCursosFavSP() async { SharedPreferences cursosFav = await SharedPreferences.getInstance(); cursosFav.clear(); print("ALL ITEMS LIST ARE DELETED"); }</pre></div></object> - Flutter How to save and show List<Object> to SharedPreferences? 如何在 SharedPreferences flutter 中保存列表数据 - How to save list data in SharedPreferences flutter 如何使用 SharedPreferences 保存列表? - How to save a list with SharedPreferences? 如何使用 SharedPreferences 从 Flutter 的列表中保存多个布尔值 - How to save multiple bool from list in Flutter with SharedPreferences 如何使用 SharedPreferences 在 Flutter 中保存字符串列表 - How can I use SharedPreferences to save a list of Strings in Flutter 如何在 Flutter 中使用 SharedPreferences 保存 DateFormat? - How to save DateFormat with SharedPreferences in Flutter? 如何将JSON的数组保存到Flutter中的SharedPreferences? - How to save an array of JSON to the SharedPreferences in Flutter? 如何正确保存 sharedPreferences 中的值? - 颤振 - How to correctly save the value in sharedPreferences? - Flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM