I want to iterate over all document in my collection and grab a particular field value and append it to a list.
How can I iterate over all document and get value of "reported" and append it to a list (rep = []). What to write inside queryValues() ?
List rep = [];
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final FirebaseAuth _auth = FirebaseAuth.instance;
void queryValues() {
// what to write here
}
CodePudding user response:
This is one of the many ways to do it. First, you get the collection from which you would like to get all documents. And you check for nullability, afterwards, you can now update your list myList
with the document list.
Look at the codebase below as an example:
import "package:cloud_firestore/cloud_firestore.dart";
final FirebaseFirestore firestore = FirebaseFirestore.instance;
void main() {
List myList = [];
Future<void> queryValues() async {
// getting all the documents from fb snapshot
final snapshot = await firestore.collection("collection").get();
// check if the collection is not empty before handling it
if(snapshot.docs.isNotEmpty) {
// add all items to myList
myList.addAll(snapshot.docs);
}
}
}
/* **DISCLAIMER** I didn't test the codebase out :) personal */
Any misunderstanding or if you need further help, Let me know.
Bye!!