1

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

3
  • 1
    You can use Shared Preference. Commented Feb 5, 2020 at 10:30
  • You can use SharedPreferences or Hive. I would suggest you to use Hive Commented Feb 5, 2020 at 10:34
  • Use SQLite to load data when offline and update data when online then use it from SQLite Commented Feb 5, 2020 at 10:41

1 Answer 1

2

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

8 Comments

Thank you for your reply, I add my code above already. Can I know where I need to put the SharedPreferences?
@dipgirl: You can do that after requesting data from API. In your code, inside response.statusCode == 200 condition.
@Ampersanda, ok I try it. Thank you
The argument type 'String' can't be assigned to the parameter type 'Map<String, dynamic>' I have error at this line User user = User.fromJson(prefs.getString("user");.
Soory, @dipgirl I had done a mistake on my answer. The correct line is: User user = User.fromJson(jsonDecode(prefs.getString("user")));
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.