Displaying the list of data got as snapshot from firebase in flutter - 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.

Related

Flutter firestore returns length 0 while there is data in firestore

I have the following code in flutter:
QuerySnapshot querySnapshot =
await _firestore.collection("user1#gmail.com").get();
List Data = querySnapshot.docs.map((doc) => doc.data()).toList();
print("Length: ${Data.length}");
Here is my firestore database:
I get the following output:
I/flutter (11484): Length: 0
The Documents for each user email is variable, so I need the length of the documents. Also I need to get to the details of each document like content and title. How to do it? Thanks.
Could you try this:
int size = await FirebaseFirestore.instance.collection(collectionPath).get(GetOptions(source:Source.server))..size;
I will recommend finding a way to store the length of documents as a field in your Cloud Firestore database because calling the get function on a whole collection means filling up the mobile phone memory. (Say you have 500,000 users at least). This makes your app slow
You could have a field called count such that when you add a document, you can use the firebase transaction to update firebase.
For example:
// Create a reference to the document the transaction will use
DocumentReference documentReference = FirebaseFirestore.instance
.collection('users')
.doc(documentId);
return FirebaseFirestore.instance.runTransaction((transaction) async {
// Get the document
DocumentSnapshot snapshot = await transaction.get(documentReference);
if (!snapshot.exists) {
throw Exception("User does not exist!");
}
// Update the follower count based on the current count
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
// Perform an update on the document
transaction.update(documentReference, {'followers': FieldValue.increment(1);});
// Return the new count
return newFollowerCount;
})
.then((value) => print("Follower count updated to $value"))
.catchError((error) => print("Failed to update user followers: $error"));
You can see more documentations here: FlutterFire

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

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

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

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