Why is vs code saying the method '.getDocuments' and the getter documents are not defined for types Query and QuerySnapshot respectively? - flutter

void _getQuestions() async {
// Query Firestore for questions with the specified tags
Query query = await _firestore
.collection('questions')
.where('tags', arrayContainsAny: widget.tags);
QuerySnapshot querySnapshot = await query.getDocuments();
setState(() {
_questions = querySnapshot.documents;
});
importing cloud_firestore.dart.
I expected the errors to leave, but they are still around.

The method to get the documents is called get() in Flutter, not getDocuments().
I recommend keeping the Firebase documentation handy for this sort of thing, for this case that'd be the section on getting multiple documents from a collection

Related

Deleting document inside subcollection by using where in Firebase Flutter?

I want to delete document inside subcollection using where, how can I achieve this?
I can delete document inside subcollection using their document Id, but in some case if we don't know the id, we need to use where method.
This is direct method.
await FirebaseFirestore.instance
.collection('customerDB')
.doc(customerId)
.delete();
I have to achieve in this case:
await FirebaseFirestore.instance
.collection('merchantDB')
.doc(merchantId)
.collection('store')
.doc(storeId).collection('customers')
.where('customerId',isEqualTo:customerId).
Use get() to get snapshot from query, then you can delete the returned result.
// return a QuerySnapshot future, which contain list of matches documents
final snapshot = await FirebaseFirestore.instance
.collection('merchantDB')
.doc(merchantId)
.collection('store')
.doc(storeId).collection('customers')
.where('customerId',isEqualTo:customerId).get()
// delete all matches
for (var doc in snapshot.docs) {
doc.reference.delete();
}

Get list of collection from firebase using flutter

I need to get list of collection like
datalist = ["2009" , "2010"]
I can use this code to print what inside the 2009 , but that not i want
final _fireStore = FirebaseFirestore.instance;
Future<void> getData() async {
// Get docs from collection reference
QuerySnapshot querySnapshot =
await _fireStore.collection('data/student_details/2009').get();
// Get data from docs and convert map to List
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
//for a specific field
print(allData);
}
and I need to know about can I filter it
Thank you.
My Firebase view
In Firebase you can not fetch a list of Collections, You have to explicitly mention the name of Collection to fetch it. It means you must have pre-knowledge of name of Collection to fetch it.

Get all documents from a Firestore collection in Flutter

I tried with different ways but i can't edit the structure of code
//First way
QuerySnapshot querySnapshot = await db.firestoreInstance.collection('user-history').get();
var list = querySnapshot.docs;
print('MY LIST ===== $list');
//Second way
final CollectionReference collectionRef = db.firestoreInstance
.collection(historyCollection);
print('MY SECOND LIST ===== $list');
collectionRef.get().then((qs) {
qs.docs.forEach((element) {
print('MY doc id ${element.id}');
});
});
In my firebase collection(historyCollection) i have four documents but the debugger returns me empty array []. Is there another way to call all documents in certain collection through flutter?
I'm trying to call this method through FutureBuilder component.
My version of firestore is: "cloud_firestore: ^0.16.0+1"
This should do the trick:
Future<List<dynamic>> getCollection(CollectionReference collection) async {
try {
QuerySnapshot snapshot = await collection.get();
List<dynamic> result = snapshot.docs.map((doc) => doc.data()).toList();
return result;
} catch (error) {
print(error);
return null;
}
}
The entire problem was not from these fragments of code. This problem is came out from this that my collections have subcollections. I read about this and i understand that subcollections can live without their ancestors and the only way to access parents is to do this is directly specify the exact path and name of the document. To work this code in my case was needed to add dummy components of my entire set of collections. For more information please look up these two topics:
-> https://firebase.google.com/docs/firestore/using-console
-> Firestore DB - documents shown in italics

CollectionReference to DocumentReference

I'm trying to perform a firestore transaction in Flutter.
Therefore I need to pass the documentReference.
There is no problem, when accessing the "lesson" document based on the identifier.
The issue is when fetching the active user pass. The where I'm trying to use returns the Query, and the .reference() returns the CollectionReference (which is not accepted by the transaction method).
How can I get the reference to the document basing on the value of its field.
To spice it up: DB rules don't allow me to read ALL the passes. I've got only access to those, that have my UserID (double checked - working).
DocumentReference lessonRef =
await _db.collection('lessons').document(lesson.identifier);
CollectionReference passRef = await _db
.collection('passes')
.where('userID', isEqualTo: user.identifier).reference();
You can get the DocumentReference of the Queried documents like so:
Firestore.instance
.collection('passes')
.where('userID', isEqualTo: user.identifier)
.snapshots()
.listen((reference) =>
data.documents.forEach((doc) => /*do what you want with doc.reference*/));
(I'm not an expert in Flutter and I could't test the code, but I based the answer in the API reference)

FLUTTER FIRESTORE -Query the field and get document id and check other field

am trying to get the searched value(userid) which is in the field of a document in firestore I want to check the other fields(status) of the document I tried this method but failed
handlesubmit(BuildContext context)async{
final QuerySnapshot searcheduserid=
await Firestore.instance.collection('users')
.where('userid',isEqualTo: userid).limit(1).getDocuments();
final userdocid=searcheduserid.documents.map((doc)=>doc.documentID);
final DocumentSnapshot getuserdoc= await Firestore.instance.collection('users')
.document(userdocid).get();
final userstatus = getuserdoc.data['status'];
// I GET AN ERROR HERE ERROR SAYS
// METHOD [](status) was called on null
if(userstatus==null){
return showdialog( context,'the entered user id status does not exist');
}
}
You probably copied an older version of your code because it is unlikely that your code compiles the following line of your program:
final DocumentSnapshot getuserdoc= await Firestore
.instance
.collection('users')
.document(userdocid).get();
The error message on my system is:
The argument type 'Iterable<String>' can't be assigned to the parameter type 'String'.
Which means that userdocid is an Iterable of type String (Iterable<String>), but a parameter which is of type String is expected.
You have multiple options of fixing the problem, but I suggest the following:
Since you are only expecting one document from your QuerySnapshot it is enough to just look at the first document.
final QuerySnapshot searchedUserId = await Firestore.instance
.collection('users')
.where('userid', isEqualTo: userid)
.limit(1)
.getDocuments();
// if it is possible that searchedUserId returns no document make sure to
// check whether searchedUserId.documents.length > 0,
// otherwise searchedUserId.documents.first will throw an error
DocumentSnapshot document = searchedUserId.documents.first;
final userDocId = document.documentID;
final DocumentSnapshot getuserdoc =
await Firestore.instance.collection('users').document(userDocId).get();
Improved Solution:
However I think your code is a bit redundant anyways, because you are looking up a field of a document which has the same value as the document ID. You could shorten the whole code to
final DocumentSnapshot getuserdoc =
await Firestore.instance.collection('users').document(userid).get();
Error calling getuserdoc.data['status']
If you get an error saying something similar to
[](status) was called on null
Then that means getuserdoc has no value. This is likely due to the fact that there is no such database entry with the given ID. Check if the ID is in your database, otherwise comment below for additional information, because the provided code had compilation errors and does not run at all.