Reputation: 860
I try to reduce connections to FireStore in my Flutter App & use cached data until I add a new item (Provider.of(context, listen: false).synced = false; - to resync).
Then pass: source: synced == true ? Source.cache : Source.serverAndCache to getDocuments()
Now all data fetch only the first time & when I need it.
But maybe there is a much more elegant way? What the right way to reduce connections & reduce costs.
I Use this code in my Task repository:
class TaskRepository extends BaseRepository {
String status;
bool synced;
TaskRepository() {
ref = db.collection('tasks');
}
Future<List<Task>> fetchDocuments() async {
List<Task> documents;
await ref
.where('ownerUID', isEqualTo: await Auth.getUID())
.where('status', isEqualTo: status ?? 'assigned')
.orderBy('createdAt', descending: true)
.getDocuments(source: synced == true ? Source.cache : Source.serverAndCache)
.then((result) {
documents = result.documents.map((doc) {
print(doc.metadata.isFromCache ? "Task from CACHE" : "Task from NETWORK");
synced = true;
return Task.fromMap(doc.data, doc.documentID);
}).toList();
}).catchError((error) {
print('Error: $error');
});
return documents;
}
}
And BaseRepository
class BaseRepository with ChangeNotifier {
final Firestore db = Firestore.instance;
final FirebaseAuth auth = FirebaseAuth.instance;
bool debug = true;
CollectionReference ref;
DateTime now = DateTime.now();
BaseRepository() {
db.settings(persistenceEnabled: true);
}
}
Upvotes: 2
Views: 555
Reputation: 688
I have been building Flutter applications using Firebase for a while and this was one of my principal concerns when I started.
After 2 months trying different things I decided to cache the data as you do so I think it is clear and shouldn’t be any problem.
Upvotes: 2