我试图通过点击或按下图标来刷新页面。示例在购物车屏幕中,我添加了产品,并且我想在单击删除按钮时删除一种产品,同时刷新页面数据.i正在从rest api获取数据。
答案 0 :(得分:0)
您应该使用ValueNotifier和ValueListenableBuilder。当更改某些值时,它们可用于更新某些小部件(子树)。
示例:
// somewhere in State class
final cartNotifier = ValueNotifier<List<Product>>(null);
final products = <Product>[];
@override
void initState() {
super.initState();
cartNotifier.value = products; // Initialize cart somehow
}
// somewhere in `build` function wrap the `cart` grid
ValueListenableBuilder<List<Product>>(
valueListenable: cartNotifier;
builder: (BuildContext context, List<Product> products, _) {
return ListView.builder(
); // This ListView shows list of `Product` items
}
);
// somewhere in `build` function when product is removed
IconButton(
icon: Icon(Icons.remove),
onPressed: () {
products.removeWhere((product) => product.id == <deletedId>);
cartNotifier.value = products;
}
);
结果cartNotifier's
的值将被更改ValueListenableBuilder重建其子树(即带有产品的ListView)