'Futurebuilder does not properly display data
I'm facing with an error right now. The data comes properly but Futurebuilder shows blank widget instead of a ListView.builder(). After rebuilding the same page by clicking the same bottomnavbar widget, it shows the data properly. Here is my Yt video demonstration of the error and here is my code:
FutureBuilder(
future: favoritesFuture,
builder: ((context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Container(
height: 50.0,
width: 50.0,
child: CircularProgressIndicator(),
);
} else {
return Container(
child: ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(
left: 8.0, right: 8.0, bottom: 16.0),
child: FavoritesContainer(
product: list[index],
),
);
}),
);
}
}),
)
Rest of the stateful widget:
late List<Product> list;
late Future favoritesFuture;
Future<List<Product>> getFavorites() async {
var repo = FavoritesRepository();
await repo.init();
list = await repo.getFavoriteProducts();
setState(() {});
return list;
}
@override
void initState() {
favoritesFuture = getFavorites();
super.initState();
}
Solution 1:[1]
I solved it.
The problem is, inside favorites_repository, I used a forEach for calculating other things related to List of Products. And I noticed that forEach DOES NOT APPLY AWAIT. So you can't run asynchronous forEach methods on anywhere. So I used this method to make it work:
Iterable l = json.decode(response.body);
List<Product> list = [];
await Future.forEach(l, (element) async {
var model = FavoriteProduct.fromMap(element as Map<String, dynamic>);
var product = await repo.getProductById(model.urunId);
list.add(product);
});
if (list.isNotEmpty) {
return list;
} else {
return [];
}```
Just use Future.forEach and you are good to go. It did work now.
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 | Zahid Tekba? |
