'Firestore queries on Flutter

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.



Solution 1:[1]

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,
  }) {..}

Solution 2:[2]

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'];
}

Solution 3:[3]

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();
          }
        }));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 creativecreatorormaybenot
Solution 2
Solution 3 aqibGenk