I am trying to put data as a temporary storage in app for 1 hour.
I am fetching the data from Firestore:
static final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<List<DocumentSnapshot>> fetchLeaderBoard() async {
final result =
await _firestore.collection('users').orderBy('points', descending: true).limit(10).get();
return result.docs;
}
And for storing it to HiveDb, I have done:
class _LeaderBoardState extends State<LeaderBoard> {
var _repository;
List<DocumentSnapshot> users;
Box box;
@override
void initState() {
_repository = Repository();
users = [];
super.initState();
openBox();
}
Future openBox() async {
var dir = await path_provider.getApplicationDocumentsDirectory();
Hive.init(dir.path);
box = await Hive.openBox('leaderBoard');
return;
}
Future<void> _fetchUsers() async {
users = await _repository.fetchLeaderBoard();
box.put('users',users);
print("HIVE DB : ");
print(box.get('users'));
}
}
Now, how to fetch it from Hivedb for 1 hour duration? And after 1 hour, data should be fetched again from Firestore.
You'll need a few classes for this. Here's a simplified example:
Note: I don't have experience with Hive, so storing and reading might be changed a bit.
You'll need to have a repository that's responsible for checking the database first for valid data, and redirecting to the api if there's no valid cached data. When new data comes in from the api, the repository will tell the database to store it.
The database keeps track of the datetime when the data was stored, to check if it is still valid after an hour.
The important thing is that the database and the firebase api should not be aware of each other. They only know about the
User
model and potentially their own models. If Hive needs other models to work with, map theUser
to those models before storing and after reading.