2

I started learning dart / flutter on my own initiative.

I have encountered one problem, which I have been trying to solve for the last 3 days.

It is about reading data from the firestore. There are a lot of documents in the firestore. I need a way to read data from multiple query.

I read the data with the streambuilder, and display it with the listview builder.

HomeScreen:

StreamBuilder<List<Vehicle>?>(
  stream: database.vehicleStream(user.uid, filters),
  builder: (context, snapshot) {
    if (snapshot.hasData) { ...

Datebase Service:

Stream<List<Vehicle>?> vehicleStream(String uid, List<ScoutFilter> filters) {
vhTest(uid, filters);
final path = APIPath.vehicle();
final reference = FirebaseFirestore.instance
    .collection(path)
    .where('datetime', isGreaterThan: limitedTime())
    .where('brand', isEqualTo: 'Mercedes-Benz')
    .where('model', isEqualTo: 'SL 350')
    .orderBy('datetime', descending: true)
    .limit(100);
final snapshots = reference.snapshots();
//print(snapshots);
return snapshots.map((snapshot) => snapshot.docs
    .map(
      (snapshot) => Vehicle.fromMap(snapshot.data(), snapshot.id),
    )
    .toList());

This works when it comes to one query for "Mercedes-Benz", "SL 350". How do I improve this and have more query for about 30 different vehicles?

Eg.

.where('brand', isEqualTo: 'Tesla')
.where('model', isEqualTo: 'Model 3')

.where('brand', isEqualTo: 'Audi')
.where('model', isEqualTo: 'Q3')

.where('brand', isEqualTo: 'Renault')
.where('model', isEqualTo: 'Clio')

etc.
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Blackbeard
  • 21
  • 3

1 Answers1

4

You should use the whereIn, as in:

.where('brand', whereIn: ['Tesla', 'Audi', 'Renault'])

See this link

Roman Jaquez
  • 2,499
  • 1
  • 14
  • 7
  • Thanks for the reply and suggestion Roman. I’ve been thinking about “WhereIn,” but I don’t think that’s the solution because I have to combine brand and model. Also, I think WhereIn has a limit of a maximum of 10 different terms, and I need a lot more. – Blackbeard Mar 09 '22 at 22:21
  • 1
    Well you can do a combination of things: you chain a couple of ***where*** statements that include the whereIn. You could also perform multiple queries against the collection by splitting your queryset across the queries (i.e you have 100 cars, well, split the 100 into ten groups of 10, perform the calls in parallel using a Future.wait since the Firestore queries return a future, then consolidate the QuerySnapshot references and extract the docs). I’d try something like that in conjunction with the whereIn. – Roman Jaquez Mar 10 '22 at 00:05