【问题标题】:Flutter Listen to of ChangeNotifier class who is a property of a ChangeNotifierFlutter Listen 的 ChangeNotifier 类,它是 ChangeNotifier 的一个属性
【发布时间】:2021-06-24 08:21:38
【问题描述】:

我有一个类 Cart,它是 ChangeNotifier。它具有项目作为属性,它也是一个 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 时,它不会立即得到反映。如何收听属性通知并触发它们?

【问题讨论】:

  • 在父级中为每个项目添加监听器,然后在监听器中通知父级
  • 能否提供样品。
  • 我喜欢使用包flutter_hookshooks_riverpod 来执行此操作。它将允许您将更改通知程序包装在 ChangeNotifierProvider 中并在您的构建方法中调用 useProvider 以在更改通知程序更新时自动重新构建

标签: flutter dart flutter-provider state-management


【解决方案1】:

就像@Selvin提到的:在父母分配方法中添加一个孩子的监听器并调用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();
  }
}

P.S.:尝试使您的示例更简单并使用更常见的类。 InvoiceDetail 类甚至不是Cart 的一部分。请改用ItemCustomer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 2021-05-21
    • 2021-07-04
    • 2021-01-13
    • 2021-02-16
    • 2022-08-14
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多