0

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
  • can you please rephrase your question and provide some detail?So that SO communiy can help you out better to get answers to your question Commented Feb 12, 2020 at 15:52

2 Answers 2

3

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

Comments

0

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

1 Comment

Maybe i don't understand exactly your problem, but for reading from SharedPreferences you can use getStringList(String key)

Your Answer

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