首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >作为ChangeNotifier属性的ChangeNotifier类的颤动监听

作为ChangeNotifier属性的ChangeNotifier类的颤动监听
EN

Stack Overflow用户
提问于 2021-03-28 02:52:26
回答 1查看 147关注 0票数 1

我有一个班车,它是ChangeNotifier。它将items作为一个属性,这也是一个ChangeNotifier。

当我更新项目的属性时,它不会立即得到反映。

代码语言:javascript
复制
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时,它不会立即得到反映。如何监听属性通知并触发它们?

EN

回答 1

Stack Overflow用户

发布于 2021-06-21 19:48:31

就像@Selvin提到的:在parents赋值方法中添加子对象的侦听器,并调用notifyListeners()

代码语言:javascript
复制
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的一部分。请改用ItemCustomer

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66834998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档