我有一个班车,它是ChangeNotifier。它将items作为一个属性,这也是一个ChangeNotifier。
当我更新项目的属性时,它不会立即得到反映。
class Cart with ChangeNotifier {
final List<Item> _items = [];
Customer customer;
setCustomer(Customer customer) {
customer = customer;
notifyListeners();
}
get items => _items;
...
removeItem(int index) {
_items.removeAt(index);
notifyListeners();
}
...
}
class InvoiceDetail with ChangeNotifier {
int id;
String name;
double price;
double qty;
InvoiceDetail(
{Key key,
this.id,
this.name,
this.price,
this.qty = 1,
})
: super();
double get lineTotal => unitPrice * qty - discount;
increaseQty() {
qty++
notifyListeners();
}
...
}当我在一个子组件中使用incrementQty时,它不会立即得到反映。如何监听属性通知并触发它们?
发布于 2021-06-21 19:48:31
就像@Selvin提到的:在parents赋值方法中添加子对象的侦听器,并调用notifyListeners()
class Cart extends ChangeNotifier {
final List<Item> _items = [];
Customer customer;
addItem(Item item) {
item.addListener(() {
notifyListeners();
});
this._items.add(item);
notifyListeners();
}
setCustomer(Customer customer) {
customer.addListener(() {
notifyListeners();
});
this.customer = customer;
notifyListeners();
}
}附言:试着让你的例子更简单,使用更多通用的类。类InvoiceDetail甚至不是Cart的一部分。请改用Item或Customer。
https://stackoverflow.com/questions/66834998
复制相似问题