How to get the List of Document Reference from a Snapshot Document resulting from a Firestore query - flutter

I can't seem to figure out how to get a List after querying a specific Firestore collection.
I want the function to:
Query the 'chat' collection on the field 'users'.
Retrieve only the document (should be only one but could be an error and there's more than one) where users, which is a LIST of Document Reference, matches two specific references: chatUserRef and authUserRef
The function should return a list of the Document References referring to this chat collection
This is what I am trying:
import 'package:cloud_firestore/cloud_firestore.dart';
Future<List<ChatsRecord>> getChatDoc(
DocumentReference chatUserRef,
DocumentReference authUserRef,
) async {
// Add your function code here!
final firestore =
FirebaseFirestore.instance; // Get a reference to the Firestore database
final collectionRef =
firestore.collection('chats'); // Get a reference to the collection
final filteredDocuments = collectionRef.where('users', isEqualTo: [
authUserRef,
chatUserRef
]); // Use the `where` method to filter the list of documents
final queryDocuments = await filteredDocuments
.get(); // You can then use the get method on this Query object to retrieve the list of documents AS a Snapshot Document (this is NOT a list of the Documents themselves).
List<ChatsRecord> listChatDocs = [];
// Cast the Snapshot Documents to a map
// Extract the Document Reference ID
// cast the query document to a map for e
// (should I forEach?)
List<ChatsRecord> listChatDocs = queryDocuments.docs.map((e) {
return FirebaseFirestore.instance.doc('chats/$e.id');
}).toList();
return listChatDocs;
}

Try using the arrayContainsAny instead of EqualTo in your where clause.
Like this:
final filteredDocuments = collectionRef.where('users', arrayContainsAny: [
authUserRef,
chatUserRef
]);

Related

add Filter Search in Streambuilder - flutter

I want to get documents from Firestore with the conditions. There are 5 conditions where 4 of which are optional. If I use where with streamBuilder, I have to create many indexes.
So, I'm going to try this method, I want to get your opinion about this.
Create a list for the store DocumentSnapshot
List<DocumentSnapshot> documents = [];
Store the snapshot to List
documents = streamSnapshot.data.docs;
Filter data like this:
if (searchText.length > 0) {
documents = documents.where((element) {
return element
.get('Title')
.toString()
.toLowerCase()
.contains(searchText.toLowerCase());
}).toList();
}

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.

Flutter firestore returning empty array on some documents

Can one explain to me what's going on with with firestore collection fetching.
I am able to fecth busescollection data under 201 but when I fecth for other 'ids' like 212 I get an empty array when there is clearly data in there.
this is the fecth function
FirebaseFirestore firestore = FirebaseFirestore.instance;
Future<dynamic> getBusesByID(int id) async {
// Create a CollectionReference called users that references the firestore collection
var lines = firestore.collection('lines').doc('$id').collection('buses');
var line = await lines.get();
return line.docs.map((e) => {'id': e.id, ...e.data()}).toList();
}
what is it with the weird behavior?

How to retrive all the documents of firestore at once using flutter?

I am building an Appointment Booking application want to retrieve all my documents from firestore at once on a button click. I used this:
Future<void> userAppointmentHistory() async {
String collectionName =
FirebaseAuth.instance.currentUser?.displayName as String;
String doc_id = "YyWqd9VlB1IdmYoIIFTq";
await FirebaseFirestore.instance
.collection(collectionName)
.doc(doc_id)
.snapshots()
.listen(
(event) {
print(
event.get("selectedDate"),
);
},
);
}
From the above code, I am getting only the specified document id details. So please help me modify the above code so that I get all the document details as I want to display these details on cards as my booked appointment history.
Here you are passing the doc id String doc_id = "YyWqd9VlB1IdmYoIIFTq";
You don't want to pass that if you want the full documents.
just pass the collection reference.
Follow the below code
fetchData() {
CollectionReference collectionReference =
FirebaseFirestore.instance.collection(collectionName);
collectionReference.snapshots().listen((snapshot) {
setState(() {
document = snapshot.docs;
});
print(document.toString);
});
}
Rudransh Singh Mahra,
It's as easy as putting text widget in our application.
Solution
You did it in right way but by mistake you have passed a specific id of documents in doc() as doc('YyWqd9VlB1IdmYoIIFTq'). you just need to remove that id from there and you may get your desired output.
What actually happens :
In your query you pass specific docId. So that it will returns that specified id document from your collection. To get all the documents from that collection you just need to do as follows,
Future<void> userAppointmentHistory() async {
String collectionName =
FirebaseAuth.instance.currentUser?.displayName as String;
// String doc_id = "YyWqd9VlB1IdmYoIIFTq";
await FirebaseFirestore.instance.collection(collectionName).doc().get()
}
And you will get your desired output if collectionName is valid and exist in firestorm database.

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