Get list of collection from firebase using flutter - 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.

Related

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

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
]);

Displaying the list of data got as snapshot from firebase in flutter

The following is the function to fetch the data from firebase, this contains a list of answers given by the user.
Future<int> getData() async {
QuerySnapshot querySnapshot = await _collectionRef.get();
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
print(allData);
return allData.length;
}
The allData is returned in the form below. I an having trouble in displaying the data inside allData in the form of listview.
Can you please help
If you want to show the data for the first document, you can do:
print(allData[0].data);
That is an array again, so if you want to then access individual values in there, have a look at arrays in Dart.

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?

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

flutter/cloud firestore : How to get only one data from doc?

I use cloud firestore with flutter and I successed to get all key/value from document but I don't successed to match only one id from doc
here is my code:
getgift() async {
final firestoreInstance = FirebaseFirestore.instance;
// Get docs from collection reference
QuerySnapshot querySnapshot = await firestoreInstance.collection("parrainage").get();
// Get data from docs and convert map to List
final mydata= querySnapshot.docs.map((doc) => doc.data()).toString();
print("$mydata");
my current output is ({key1: value1}, {key2: value2})
I trie to match only data from key1 for this exemple.
thank you
}
The following code will return a DocumentSnapshot object.
DocumentSnapshot snapshot = await firestoreInstance.collection("parrainage").doc("key1").get();
You can access its value by doing the following:
dynamic x = snapshot.data(); // will return value1
If I understand correctly, you only want to get value1 to be got. If that's so, then simply do this:
final mydata= querySnapshot.docs.firstWhere((element) => element.data().containsKey(key1));
Or, if ya want to get only the data with key as key1 (instead of getting all the keys and values), do this:
QuerySnapshot querySnapshot = await firestoreInstance.collection("parrainage").doc(key1).get();
final mydata= querySnapshot.get(key1);
Cheers