Flutter. Create a List<String> of the firestore documents and collections - flutter

I'm trying to fetch a list of documents (documentID) from Firestore and add it to a List. I have seen some options but since I am a little new in this area, perhaps the obvious is becoming difficult for me. And I don't know exactly where in the code those lines should go, for example in an initState.
This is one of the options that I have chosen, but it only generates instances and not the name of the documents as such.
final QuerySnapshot result =
await Firestore.instance.collection('submits').getDocuments();
final List<DocumentSnapshot> documents = result.documents;
List<String> myListString = []; // My list I want to create.
myListString.add(documents); // The way I try to add the doc list to my String list.
Example the data base. I want to get a list of the document ID to a List-String-
enter image description here
And if possible, you could tell me if there is an analogous way to apply it to obtain a List but in the case of two or more collections.

It seems like what you want is a list of the document ids, right?
If so, this should work:
final QuerySnapshot result =
await Firestore.instance.collection('submits').getDocuments();
final List<DocumentSnapshot> documents = result.documents;
List<String> myListString = []; // My list I want to create.
documents.forEach((snapshot) {
myListString.add(snapshot.documentID)
});

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.

How can I get a collection inside a QuerySnapshot

On the explore page, I get() the entire users collection to create a user list and search results. Inside each of those user documents is a collection posts that I also need to get to create a GridView of each post. I want to reuse that users collection QuerySnapshot instead of fetching each posts collection again to save money. Is this possible?
Here is my current function:
void fetchUsers() async {
final userRef = FirebaseFirestore.instance.collection('users');
final QuerySnapshot result = await userRef.get();
final docs = result.docs.asMap();
docs.forEach((index, value) {
final profile =
ProfileObject.fromJson(value.data() as Map<String, dynamic>);
usersList.add(UserSearchResult(profile, value.id));
/// Below is the code for getting the posts, not working, need ideas
final QuerySnapshot postsResult = value.get('posts');
final posts = postsResult.docs.asMap();
posts.forEach((index, value) {
final post = Post.fromJson(value.data() as Map<String, dynamic>);
postsList.add(post);
});
});
print(usersList);
print(postsList);
}
Here is the structure of my Firestore:
users
uid (doc)
posts (collection)
info (fields)
uid (doc)
posts (collection)
info (fields)
It is not possible to call a collection to get all sub-collections. You should restructure your database to include sub-collection data in document itself. You can use a map or list for that. But remember, calling everything in one go may end up in slow performance and you might end up losing your customers. So the best way is to include the info in every posts' documents. That way, you won't loss your money and user won't feel lag in performance.
It is not possible. You fetch a document, then fetch the (sub)collection under it.
Subcollection data are not included in the initial document snapshots because Firestore queries are shallow. There shouldn't be any cost savings that you can do there?
See the similar Q&A:
Firestore: Get subcollection of document found with where

DocumentID search in Firestore with a List

Can i search a Firestore DocumentID with a List<String>?
I am trying to search through my collection with some selection of documentID in a List. The List will consist of few String. Can I search through the Firestore collection using this?
This is the List:
List<String> _selectedBusStop = List<String>();
This is the code I used in finding the DocumentID based on the list that is in here.
Future <void> saveRoute(_selectedBusStop) async{
Firestore.instance.collection('markers').where('BusstopName', isEqualTo: _selectedBusStop)
.snapshots().listen((location) {
if(location.documents.isNotEmpty){
for (int i = 0; i < location.documents.length; i++){
initRoute(location.documents[i].data, location.documents[i]);
}
}
});
setState(() {
});
}
I am using where and isEqualTo or is this approach wrong? Any idea how to make it work for this part? Thank you in advance for your help.
Update:
This is how my Firestore looks like:
The List have some of the BusstopName but not all of it. I do not want to retrieve all the data from the Firestore just the one that is in the List. Sorry for causing so many misunderstanding.
Use the whereIn operator, like this:
Future <void> saveRoute(_selectedBusStop) async{
Firestore.instance.collection('markers').where('BusstopName', whereIn: _selectedBusStop)
.snapshots().listen((location) {
if(location.documents.isNotEmpty){
for (int i = 0; i < location.documents.length; i++){
initRoute(location.documents[i].data, location.documents[i]);
}
}
});
setState(() {
});
}
Assuming your documents have a unique id stored in the field BusstopName and also the documents actual id matches the content of this field, you have 2 possibilities.
(1) .where query
query data with collection("markers").where("BusstopName", "=", "yourBuststopId").
this returns a querySnapshot Object, on which you can call .size to check if there were any documents with that Id found (could be more than 1 if you have an inconsistent database).
(2) .doc query
query data with collection("markers").doc("yourBuststopId")
this returns a documentSnapshot Object, on which you can call .exist to check if the document actually exsists.
In both cases you need to do 1 query per Id, because Firestore queries only support equality and range operations. See this similar SO question. I would suggest to do the queries asynchronously, otherwise the time to execute will increase with the size of the array.
If you are concerned about costs, you only get billed for the results that actually return documents that exist.
you might also try this:
FirebaseFirestore.instance
.collection('markers')
.where('BusstopName', arrayContainsAny: ['Utar Bus Stop', 'Garden Bus Stop'])
.get()
.then(...);
Taken from the examples documentation

Flutter get document from collection without knowing its ID but knowing filed name

I'm trying to get only one document from the collection.
I have Collection named cards, in this collection I've created Documents with Auto ID, each Document have field Name. In one of the documents fild Name = Horse.
How can I retrive this document and all the fields related to it?
The problem that I've faced is that all of the documentation relay on listviews. In my case I don't have a need and use of listview.
Try this:
final colRef = Firestore.instance.collection("your_path");
final snapshot = await colRef.where("Name", isEqualTo: "Horse").limit(1).getDocuments();
final docSnapshot = snapshot.documents[0];