Flutter - 在本地保存 json 数据以备将来使用

Flutter - save json data local for a future list

所以,我的问题是,我想在本地保存一个 json 数据,这样用户就可以看到他保存的项目。

  Future saveData() async {
    SharedPreferences kitSalvos = await SharedPreferences.getInstance();

    kitSalvos.setString('id', id);
    kitSalvos.setString('content', content);
  }

内容为json数据。

这就是我正在做的,但是,当我尝试创建它的列表时,它带来了其他共享偏好。

  _getDataKits() async {
    SharedPreferences kitSalvos = await SharedPreferences.getInstance();
    print(kitSalvos.getKeys());
  }

输出:

{isLogged, senha, email, 20210408, 20210408040319, token, id, content}

我只想带上已保存的项目(即 ID 和 CONTENT)sharedpreferences...

有办法让它分离吗?所以我只能得到ID和CONTENT...

另外,把它变成一个,喜欢并反对:

 kitsalvos = [ id: ID, content: CONTENT ];

将有超过 1 个保存的项目,所以我需要将所有项目分开存储...

您可以将 JSON 保存在字符串上,当您必须使用它时,您可以获取字符串并解析为模型。

创建此模型:

// To parse this JSON data, do
//
//     final kitModel = kitModelFromMap(jsonString);

import 'dart:convert';

KitModel kitModelFromMap(String str) => KitModel.fromMap(json.decode(str));

String kitModelToMap(KitModel data) => json.encode(data.toMap());

class KitModel {
KitModel({
    this.the20210408,
    this.isLogged,
    this.senha,
    this.email,
    this.the20210408040319,
    this.token,
    this.id,
    this.content,
});

String the20210408;
bool isLogged;
String senha;
String email;
String the20210408040319;
String token;
int id;
String content;

factory KitModel.fromMap(Map<String, dynamic> json) => KitModel(
    the20210408: json["20210408"],
    isLogged: json["isLogged"],
    senha: json["senha"],
    email: json["email"],
    the20210408040319: json["20210408040319"],
    token: json["token"],
    id: json["id"],
    content: json["content"],
);

Map<String, dynamic> toMap() => {
    "20210408": the20210408,
    "isLogged": isLogged,
    "senha": senha,
    "email": email,
    "20210408040319": the20210408040319,
    "token": token,
    "id": id,
    "content": content,
    };
}

正在保存套件 ->

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('content', content);

获取工具包 ->

dart:convert


SharedPreferences prefs = await SharedPreferences.getInstance();
String KitJson = prefs.getString("content");

if (KitJson != null) {
  kit = KitModel.fromMap(json.decode(KitJson));
}

现在您可以使用

print({kit.id, kit.content, kit.toke, kit.isLogged}); //And so on