dipgirl
dipgirl

Reputation: 690

How to save data from API temporary in device Flutter

When I open my apps, every time I need to wait for it loading the data from API. I want to save data on Local Storage temporary to make app works offline and also can load the data faster. I want to get data from api, json data and save them to local storage. Can I know what method or can use any package? Thanks in advance

Upvotes: 1

Views: 486

Answers (1)

I would recommend using SharedPreferences + JSON. For example, you may have a user object:

class User {

  final String name;
  final String email;

  User(this.name, this.email);

  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];

  Map<String, dynamic> toJson() =>
    {
      'name': name,
      'email': email,
    };
}

Then what you need to do is:

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("user", jsonEncode(user));

And to recover the object:

SharedPreferences prefs = await SharedPreferences.getInstance();
User user = User.fromJson(jsonDecode(prefs.getString("user")));

Upvotes: 2

Related Questions