From server I am returing json array which contains data of key,value type. I could not find the error. Please help me someone. This is my edited code. I am now getting error: RangeError(index): Index out of range: no Indices are valid: 0
Future<Products> fetchProducts() async {
final response =
await http.get(Uri.parse('url'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Products.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load Products');
}
}
class Products {
final List hotdeals = [];
Products({
required List hotdeals,
});
factory Products.fromJson(Map json) {
return Products(hotdeals: json['hotdeals']
);
}
}
And in my MyAppState class (I am showing just necessary portions):
late Future<Products> futureProducts;
@override
void initState() {
super.initState();
futureProducts = fetchProducts();
}
And I am prining like this:
FutureBuilder<Products>(
future: futureProducts,
builder: (context, snapshot) {
if (snapshot.hasData) {
(snapshot.data!.hotdeals[0] as Map)
.forEach((key, value) {
print(value[key]['price']);
});
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
My json response is:
{"hotdeals":[{"id":"10","name":"Platinum
Pack","image":"uploads\/1606908813_ppack.jpg","price":"699.00"},{"id":"9","name":"Standard
Pack","image":"uploads\/1606908536_spack.jpg","price":"499.00"}]}