Maybe it's a newbie question, but I'm learning flutter and some stuffs like async, await, Future, doesn't fit in my mind yet. Anyway, what I want to do is get the value from "field.documents[index]["name"]" and built a List. Here is my code:
String productName;
Stream<QuerySnapshot> productRef = Firestore.instance
.collection("stores")
.document(name)
.collection("products")
.snapshots();
productRef.forEach((field) {
field.documents.asMap().forEach((index, data) {
productName = field.documents[index]["name"];
//IF I PRINT HERE, IT SHOWS THE PRODUCTS.
});
});
BUT IF I PRINT HERE, I GOT A NULL VALUE
I want to get productName outside the forEach. When I print, it first prints null. I´ll post my entire function too:
List mapToList({DocumentSnapshot doc, List<DocumentSnapshot> docList}) {
if (docList != null) {
List<Store> storeList = [];
docList.forEach((document) {
String name = document.data[StringConstant.nameField];
num score = document.data[StringConstant.scoreField];
String delivery = document.data[StringConstant.deliveryField];
String photo = document.data[StringConstant.photoField];
String description = document.data[StringConstant.descriptionField];
String open = document.data[StringConstant.openField];
String close = document.data[StringConstant.closeField];
GeoPoint geoPoint = document.data[StringConstant.positionField]
[StringConstant.geopointField];
bool isOpen = document.data[StringConstant.isOpenField];
final currentHour = DateTime.now();
final openHour = DateTime.parse(open).hour;
final closeHour = DateTime.parse(close).hour;
int openMin = DateTime.parse(open).minute;
int closeMin = DateTime.parse(close).minute;
if (openHour <= currentHour.hour && currentHour.hour <= closeHour) {
isOpen = true;
if ((currentHour.hour == openHour && currentHour.minute < openMin) ||
(currentHour.hour == closeHour &&
currentHour.minute > closeMin)) {
isOpen = false;
}
} else {
isOpen = false;
}
final double meter = distance(
LatLng(latitude, longitude),
LatLng(geoPoint.latitude, geoPoint.longitude),
);
String productName;
Stream<QuerySnapshot> productRef = Firestore.instance
.collection("stores")
.document(name)
.collection("products")
.snapshots();
productRef.forEach((field) {
field.documents.asMap().forEach((index, data) {
productName = field.documents[index]["name"];
});
});
if (meter <= range && isOpen == true) {
Store otherStore = Store(name, photo, score.toDouble(), delivery,
meter, description, productName, 10.0, "");
storeList.add(otherStore);
}
});
return storeList;
} else {
return null;
}
}
Can somebody help me? I know its something with asynchronous programming, but I'm learning. Thanks!!!