I’m trying to return data from my future provider and use it inside my GridView widget but I got that error.
The URL is returning status and data: {"status":"success","data":[{"items_id":5,etc}}
Here is my fake_product_repository.dart:
class ProductsRepository {
Future<List<Product>> fetchProductsList() async {
final url =
Uri.parse('http://localhost:80/ecommerceflutter/items/items.php');
final response = await http.get(url);
if (response.statusCode == 200) {
final jsonData = json.decode(response.body);
List<Product> products = [];
for (var productData in jsonData) {
Product product = Product.fromJson(
productData); // Replace with your own deserialization logic
products.add(product);
}
return products;
} else {
throw Exception('Failed to fetch products');
}
}
}
final productsRepositoryProvider = Provider<ProductsRepository>((ref) {
// You can initialize your repository here if needed
return ProductsRepository();
});
final productsListProvider = FutureProvider<List<Product>>((ref) async {
final repository = ref.watch(productsRepositoryProvider);
final products = await repository.fetchProductsList();
return products;
});
This is product_grid.dart used my in main.dart:
class ProductsGrid extends ConsumerWidget {
const ProductsGrid({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final productsListValue = ref.watch(productsListProvider);
// return Text("heafasd");
return productsListValue.when(
loading: () => const CircularProgressIndicator(),
error: (err, stack) => Text('Error $err'),
data: (products) => ProductsLayoutGrid(
itemCount: products.length,
itemBuilder: (_, index) {
final product = products[index];
return ProductCard(
product: product,
);
},
),
);
}
}
class ProductsLayoutGrid extends StatelessWidget {
const ProductsLayoutGrid(
{super.key, required this.itemCount, required this.itemBuilder});
final int itemCount;
final Widget Function(BuildContext, int) itemBuilder;
@override
Widget build(BuildContext context) {
return GridView.count(
crossAxisCount: 4,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
children: [
for (var i = 0; i < itemCount; i++) itemBuilder(context, i),
],
);
}
}
Also in case I have multiple requests should I create Future provider as I did, is there anyway to wrap everything up.
2
Answers
The answer was changing the url to
http://10.0.2.2/ecommerceflutter/items/items.php
As for the response,
data
contains the items.