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
1 Answer
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")));
8 Comments
dipgirl
Thank you for your reply, I add my code above already. Can I know where I need to put the SharedPreferences?
Lucky
@dipgirl: You can do that after requesting data from API. In your code, inside
response.statusCode == 200 condition.dipgirl
@Ampersanda, ok I try it. Thank you
dipgirl
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");.
Vinícius Assis Neves
Soory, @dipgirl I had done a mistake on my answer. The correct line is: User user = User.fromJson(jsonDecode(prefs.getString("user")));
|
Shared Preference.SharedPreferencesorHive. I would suggest you to useHive