In Dart Flutter if else conditions causing problems. In this method with if else conditions the forEach loop is not working properly as it does not allowing the print statement to print each key and value in the map.
Data for map comes from the firestore database
But when I remove if else conditions , then it is working properly Please help.
CODE
Future<List<ReviewModel>> getCakeReview(String cakeId) async {
CollectionReference snap = types.doc(cakeId).collection('Reviews');
List<ReviewModel> list = [];
ReviewModel model = ReviewModel("", "", 0, "");
String userName = "";
String userDP = "";
String review = "";
int rating = 0;
await snap.get().then((value) {
for (var result in value.docs) {
Map<String, dynamic> map = result.data() as Map<String, dynamic>;
print(map);
int i = 0;
map.forEach((key, value) {
print(key.toString() ":" value.toString());
print(i );
if (key.toString() == 'userName') {
userName = value.toString();
} else if (key.toString() == 'userDP') {
userDP = value.toString();
} else if (key.toString() == 'rating') {
rating = value;
} else {
review = value.toString();
}
});
model = ReviewModel(userName, userDP, rating, review);
list.add(model);
}
});
print("FS");
return list;
}
CodePudding user response:
replace
map.forEach((key, value) {
print(key.toString() ":" value.toString());
print(i );
if (key.toString() == 'userName') {
userName = value.toString();
} else if (key.toString() == 'userDP') {
userDP = value.toString();
} else if (key.toString() == 'rating') {
rating = value;
} else {
review = value.toString();
}
});
with
userName = map['userName'];
userDP = map['userDP'];
rating = map['rating'];
review = map['review'];
to eliminate the "for-switch" anti-pattern.
CodePudding user response:
Now I got what was the problem,
I try to store the value(which is not integer when returned from firebase I think) into the rating variable which is an integer type
so what I did is, parsed the value to integer and it worked fine.
Code
map.forEach((key, value) {
print(key.toString() ":" value.toString());
print(i );
if (key.toString() == 'userName') {
userName = value.toString();
} else if (key.toString() == 'userDP') {
userDP = value.toString();
} else if (key.toString() == 'rating') {
rating =int.parse(value);
} else {
review = value.toString();
}
});