40

How can I use the .where() in FlutterFire to perform queries for Firestore? Because the docs and example doesn't cover this I'm confused. I haven't found other questions on this here so I hope I'm not asking duplicate.

4 Answers 4

73

Example below go through every document in the collection 'fields', and filter on 'grower`. There is no documentation on that, but you may check the source code.

import 'package:cloud_firestore/cloud_firestore.dart';

Firestore.instance.collection('fields').where('grower', isEqualTo: 1)
    .snapshots().listen(
          (data) => print('grower ${data.documents[0]['name']}')
    );

From source code:

  Query where(
    String field, {
    dynamic isEqualTo,
    dynamic isLessThan,
    dynamic isLessThanOrEqualTo,
    dynamic isGreaterThan,
    dynamic isGreaterThanOrEqualTo,
    bool isNull,
  }) {..}
Sign up to request clarification or add additional context in comments.

11 Comments

This helps. Thanks. Documentation needs to be improved on the plugin.
Hello, i'd like to know if you can do 'where' filtering for multiple values, putting more than one value in the clausule. Example: where age is high than x, and wheigh is less than, etc.
Jorge you can't query with range over different values
Hey @Jorge and other people who are still looking for the multiple conditions query, I understand that this is possible using multiple where clauses.
> Show me the code: @override Stream<List<UserFeedEntity>> userfeeds(String userID) { return firestore.collection(path).where("userID", isEqualTo: userID).where("projectID", isEqualTo: "sc_demo_project1").snapshots().map((snapshot) { return snapshot.documents.map((doc) { return UserFeedEntity( doc['projectID'], doc['installationID'], doc['userID'], doc['feeds'].cast<String>(), ); }).toList(); }); }
|
18

Update (Null safety code)

Since lot of classes are now either deprecated or completely removed, use this code for Flutter 2.0 and above.

final querySnapshot = await FirebaseFirestore.instance
    .collection('employees')
    .limit(10)
    .where('age', isGreaterThan: 30)
    .get();

for (var doc in querySnapshot.docs) {
  // Getting data directly
  String name = doc.get('name');
  
  // Getting data from map
  Map<String, dynamic> data = doc.data();
  int age = data['age'];
}

Comments

2

this if you use streambuilder

StreamBuilder<QuerySnapshot>(
        stream: feed.where('uid', isEqualTo: 'aaaaaaaaaaaaa').snapshots(),
        builder: (_, snapshot) {
          if (snapshot.hasData) {
            return Column(
              children: snapshot.data.docs
                  .map((e) => itemGrid(
                        e.data()['username'],
                        e.data()['uid'],
                        e.data()['uavatarUrl'],
                        e.data()['imageUrl'],
                        e.data()['desc'],
                      ))
                  .toList(),
            );
          } else {
            print('null');
            return Container();
          }
        }));

Comments

0

Example data

To get started, write some data about cities so we can look at different ways to read it back:

final cities = db.collection("cities");
final data1 = <String, dynamic>{
  "name": "San Francisco",
  "state": "CA",
  "country": "USA",
  "capital": false,
  "population": 860000,
  "regions": ["west_coast", "norcal"]
};
cities.doc("SF").set(data1);

final data2 = <String, dynamic>{
  "name": "Los Angeles",
  "state": "CA",
  "country": "USA",
  "capital": false,
  "population": 3900000,
  "regions": ["west_coast", "socal"],
};
cities.doc("LA").set(data2);

final data3 = <String, dynamic>{
  "name": "Washington D.C.",
  "state": null,
  "country": "USA",
  "capital": true,
  "population": 680000,
  "regions": ["east_coast"]
};
cities.doc("DC").set(data3);

final data4 = <String, dynamic>{
  "name": "Tokyo",
  "state": null,
  "country": "Japan",
  "capital": true,
  "population": 9000000,
  "regions": ["kanto", "honshu"]
};
cities.doc("TOK").set(data4);

final data5 = <String, dynamic>{
  "name": "Beijing",
  "state": null,
  "country": "China",
  "capital": true,
  "population": 21500000,
  "regions": ["jingjinji", "hebei"],
};
cities.doc("BJ").set(data5);

Simple queries

  1. The following query returns all cities with state CA:
// Create a reference to the cities collection
final citiesRef = db.collection("cities");

// Create a query against the collection.
final query = citiesRef.where("state", isEqualTo: "CA");
  1. The following query returns all the capital cities:
final capitalcities =
    db.collection("cities").where("capital", isEqualTo: true);

Execute a query

After creating a query object, use the get() function to retrieve the results:

db.collection("cities").where("capital", isEqualTo: true).get().then(
      (res) => print("Successfully completed"),
      onError: (e) => print("Error completing: $e"),
    );

Refer the docs for more information

2 Comments

Not very helpful just to copy the documentation. I think the doc falls short, how to retrieve the data in the last code snippet (after the then). This explains it better: stackoverflow.com/a/71894480/13648205
@w461 then refer that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.