I am new in Flutter, this is my first project in Flutter. I want to do a project that once data are loaded from API, they're cached in the device. Next time it can be loaded very fast even if my device is offline. I here that can using Dio package with dio cache manager package for caching server's json response. And then using cache image package to cache images. Anyone can give me some example how to write the code? Thanks in advance
-
why not save the data in sqlite db... it is local to user's deviceDAMMAK– DAMMAK2020-02-05 09:02:05 +00:00Commented Feb 5, 2020 at 9:02
-
you can use moor.John Joe– John Joe2020-02-05 09:14:24 +00:00Commented Feb 5, 2020 at 9:14
-
@DAMMAK thank you for your reply, you means that save my API response into sqlite? Sorry I am first time using flutterqing– qing2020-02-05 09:50:47 +00:00Commented Feb 5, 2020 at 9:50
-
@JohnJoe Thank you for your reply. My data is from API, also can use is package? Sorry I am first time using flutterqing– qing2020-02-05 09:52:39 +00:00Commented Feb 5, 2020 at 9:52
-
use shared preferences to store responseNavin Kumar– Navin Kumar2020-02-05 14:33:58 +00:00Commented Feb 5, 2020 at 14:33
3 Answers
Another best way for caching in flutter is the use of the hive.
And it retrieves data faster than Sqflite and Shared preferences
For example, you can check this GitHub repo:https://github.com/shashiben/Anime-details
This will show how to cache the rest API data into the hive and for the next time it will show data from the hive.
I think this answer helped you
1 Comment
Yeah i'd recommend the sqflite package for flutter, i've just figured out how to use it to solve this same issue! I learnt it using this YouTube video: https://youtu.be/1BwjNEKD8g8.
2 Comments
Try shared preferences https://pub.dev/packages/shared_preferences,
Just Decode your response as string and save to sharePreference, and Encode that String to Object when you need.
import 'package:shared_preferences/shared_preferences.dart';
//storing response as string
SharedPreferences sharedPref = await SharedPreferences.getInstance();
Map decode_options = jsonDecode(jsonString);
String user = jsonEncode(User.fromJson(decode_options));
sharedPref.setString('user', user);//storing
//getting string and converting into Object
SharedPreferences sharedPref = await SharedPreferences.getInstance();
Map userMap = jsonDecode(sharedPref.getString('user')); //retriving
var user = User.fromJson(userMap);
class User {
final String name;
final String age;
User({this.name, this.age});
factory User.fromJson(Map<String, dynamic> parsedJson) {
return new User(
name: parsedJson['name'] ?? "",
age: parsedJson['age'] ?? "");
}
Map<String, dynamic> toJson() {
return {
"name": this.name,
"age": this.age
};
}
}