'Flutter function that returns conditional does not give correct result
I have a code like this:
//...
child: ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage("${snapshot.data!.docs[index].data()['urunFotografi']}"),
),
title: Text(snapshot.data!.docs[index].data()["urunAdi"], style: TextStyle(fontSize: 20),),
subtitle: Text(adetVeyaKilo().toString(), style: TextStyle(fontSize: 15),),
),
// ...
// ...
Future<String> adetVeyaKilo() async {
String state = "";
FirebaseFirestore.instance.collection('bolatAktar').where('urunAdi', isEqualTo: urunAdi).get().then((value) {
value.docs.forEach((element) {
if (element.data()["urunBirimi"] == "Adet") {
state = "Adet";
}
if (element.data()["urunBirimi"] == "Kilo") {
state = "Kilo";
}
});
});
return state;
}
// ...
With the codes I wrote, I am trying to make a return according to the data coming from Firebase Firestore.
But when trying to print to subTitle it prints like this: Instance of Future<String>
Why does this problem occur? How can I solve it?
Thanks in advance for your help.
Solution 1:[1]
Try this:
Future<String> adetVeyaKilo() async {
String state = "";
await FirebaseFirestore.instance.collection('bolatAktar').where('urunAdi', isEqualTo: urunAdi).get().then((value) {
value.docs.forEach((element) {
if (element.data()["urunBirimi"] == "Adet") {
setState((){
state = "Adet";
});
}
if (element.data()["urunBirimi"] == "Kilo") {
setState((){
state = "Kilo";
});
}
});
Solution 2:[2]
You need to write await before FirebaseFirestore.instance.collection('bolatAktar')....
Or you can do like this. This one is better
final response = await FirebaseFirestore.instance.collection('bolatAktar').where('urunAdi', isEqualTo: urunAdi).get();
for(int i=0;i<response.docs.length;i++){
if(response.docs[i].data()["urunBirimi"] == "Adet"){
state = "Adet"
}
if(response.docs[i].data()["urunBirimi"] == "Kilo"){
state = "Kilo";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saitoh Akira |
| Solution 2 | Yunus Emre Çelik |

