I made a function to read a the data from a specific document and it works(code below)
Future<List<String>> getAllServicesFromDatabase()async{
List<String> services = [];
FirebaseFirestore db = FirebaseFirestore.instance;
DocumentSnapshot<Map<String, dynamic>> results = await db.collection(dbCollection).doc(servicesDocument).get();
if(results.data() != null){
Map<String,dynamic> fetchedData = results.data()!;
for(String service in fetchedData.keys.toList()){
services.add(service);
}
}
return services;
}
Table belonging to the first code sample:
Now I’d like something similar but this time I don’t know the name of the documents. I’d like to create a Function that returns a Lists of document names so that I can then Read each individual document.
(my failed attempt below)
class Customer {
Customer({
required this.document,
required this.customer,
});
final String document;
final Map<String,dynamic> customer;
}
Future<List<Customer>> getAllCustomersFromDatabase()async{
List<Customer> customers = [];
FirebaseFirestore db = FirebaseFirestore.instance;
QuerySnapshot<Map<String, dynamic>> response = await db.collection(customersCollection).get();
response.docs.map((doc){
String docName = doc.id;
Map<String, dynamic> document = doc.data();
Customer customer = Customer(
document: docName,
customer: document,
);
print(customer.document);
print(customer.customer);
});
return customers;
}
2
Answers
Your
getAllCustomersFromDatabase
function always returns an empty list. It starts by creating an empty list namedcustomers
, performs a Firestore query, does absolutely nothing withcustomers
after the query is done, and then returns the unchanged empty list.You probably want to actually populate the
customers
list at some point. Maybe you meant to return a Customer object fromresponse.docs.map
, then return the result of the map.Problem:
The current code is mapping over the
response.docs
and creating aCustomer
object on each run but not doing anything with either the createdCustomer
object or theresult
of the map:Solution:
To fix this, do the following:
Customer
object at the end of the map block.customers
variable.Like this: