import 'package:flutter/widgets.dart'; import 'package:thesis_shop/models/product.dart'; import 'package:thesis_shop/models/remote_resource.dart'; import 'package:thesis_shop/service/product_service.dart'; class ProductStoreImplementation extends StatefulWidget { final Widget child; final ProductService productService; const ProductStoreImplementation({ Key? key, required this.child, required this.productService, }) : super(key: key); @override _ProductStoreImplementationState createState() => _ProductStoreImplementationState(); } class _ProductStoreImplementationState extends State { RemoteResource> products = RemoteResource.loading(); @override void initState() { super.initState(); loadProducts().catchError( (err) => setState( () { products = RemoteResource.error(err.toString()); }, ), ); } Future loadProducts() async { final remoteProducts = await widget.productService.fetchProducts(); setState(() { products = RemoteResource.finished(remoteProducts); }); } @override Widget build(BuildContext context) { return ProductStore(products: products, child: widget.child); } } class ProductStore extends InheritedWidget { const ProductStore({ Key? key, required this.products, required Widget child, }) : super(key: key, child: child); final RemoteResource> products; List get mustProducts => products.asFinished().value; List? get productsOrNull { if (products is FinishedRemoteResource) { return mustProducts; } return null; } static ProductStore of(BuildContext context) { final ProductStore? result = context.dependOnInheritedWidgetOfExactType(); assert(result != null, 'No ProductStore found in context'); return result!; } @override bool updateShouldNotify(ProductStore oldWidget) { return oldWidget.products != products; } }