Create Json Arrays and List with SharedPreferences

2020-05-01 12:06发布

问题:

I have been using shared_preferences to create and write in Json Files. The Problem i facing is i dont know how to create a Json Array and a List in shared_preferences.

I want to save and read a Json List.

  read(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return json.decode(prefs.getString(key));
  }

  save(String key, value) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(key, json.encode(value));
  }

  remove(String key) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove(key);
  }
} ```

回答1:

Example on DartPad.

Save a list to SharedPreferences with setStringList:

  const String key = "users";

  List<User> users = [User(name: "tester")];
  List<String> jsonList = users.map((user) => user.toJson()).toList();
  SharedPreferences prefs = await SharedPreferences.getInstance();

  prefs.setStringList(key, jsonList);

Read a list from SharedPreferences with getStringList:

  jsonList = prefs.getStringList(key);

  users = jsonList.map((json) => User.fromJson(json)).toList();

The user class with json convert: JSON and serialization

class User {
  String name;
  int age;

  User({
    this.name,
    this.age,
  });

  factory User.fromJson(String str) => User.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory User.fromMap(Map<String, dynamic> json) => User(
        name: json["name"],
        age: json["age"],
      );

  Map<String, dynamic> toMap() => {
        "name": name,
        "age": age,
      };
}


回答2:

Just map your json array to List<String> and after you can use the setStringList function provided in shared_preferences.dart

  /// Saves a list of strings [value] to persistent storage in the background.
  ///
  /// If [value] is null, this is equivalent to calling [remove()] on the [key].
  Future<bool> setStringList(String key, List<String> value) =>
      _setValue('StringList', key, value);


标签: flutter dart