You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
2.0 KiB
76 lines
2.0 KiB
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<ProductStoreImplementation> {
|
|
RemoteResource<List<Product>> products = RemoteResource.loading();
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
loadProducts().catchError(
|
|
(err) => setState(
|
|
() {
|
|
products = RemoteResource.error(err.toString());
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> 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<List<Product>> products;
|
|
List<Product> get mustProducts => products.asFinished().value;
|
|
List<Product>? get productsOrNull {
|
|
if (products is FinishedRemoteResource) {
|
|
return mustProducts;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
static ProductStore of(BuildContext context) {
|
|
final ProductStore? result =
|
|
context.dependOnInheritedWidgetOfExactType<ProductStore>();
|
|
assert(result != null, 'No ProductStore found in context');
|
|
return result!;
|
|
}
|
|
|
|
@override
|
|
bool updateShouldNotify(ProductStore oldWidget) {
|
|
return oldWidget.products != products;
|
|
}
|
|
}
|
|
|