【问题标题】:How to update UI when remove and add list item with provider使用提供程序删除和添加列表项时如何更新 UI
【发布时间】:2021-03-20 10:54:17
【问题描述】:

我在提供程序模型中有一个列表项,我想在添加或删除项时为其设置一个观察者侦听器,同时在无状态小部件中更新相关 UI 的一部分(而不是在有状态小部件中使用 setState)。

// Provider
class AppState extends ChangeNotifier {
  List<Item> _items;
  List<Item> get items => _items;
  Future<void> addItem(...) async {
    ...
    notifyListeners();
  }
  Future<void> deleteItem(...) async {
    ...
    notifyListeners();
  }
}

// UI
class _itemList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var appState = context.watch<AppState>();  // If I watch the list, it will rebuild all of it.
    return ListView.builder(
      itemCount: appState.items.length,
      itemBuilder: (context, index) {
        final item = appState.items[index];
        return ListTile(  // How to observer the item of list instead to rebuild all of it?
          title: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(item.name),
              Icon(Icons.keyboard_arrow_right, color: Colors.grey)
            ],
          )
      });
  }
}

【问题讨论】:

  • 最好的方法是在 dart 中使用流。尝试学习集团模式。 Provider 有不同的用途,它不用于重建特定的小部件。尝试学习流如何在flutter和flutter_bloc或rxdart中工作

标签: flutter flutter-provider


【解决方案1】:
  • 将with 与ChangeNotifier 一起使用,而不是extends,因为ChangeNotifier 是一个mixin 而不是一个类。

  • 不确定您是否可以使用当前设置观察单个项目,因为您的 Changenotifier 中有 List 项目,这是唯一的财产持有状态。 虽然,还有另一种方法可以使用 context.select&lt;AppState&gt;((appState) =&gt;appState.items) 使用提供程序来观察单个属性,但这只会观察项目。

  • 但是,如果您还想保持单个项目的状态,这在您尝试在另一个屏幕上查看单个项目的内容时很有帮助,您可以这样做

class AppState with ChangeNotifier {
  List<Item> _items;
  List<Item> get items => _items;
  
   Item _item;
   Item get item => _item;


   setCurrentItem(int index){
      _item= _tems[index];
      notifyListners();
   }

...

 @override
  Widget build(BuildContext context) {
    var item = context.select<AppState>((appSatet)=> appState.item);


// set the item using setCurrentItem() to observe one item.

但是由于您正在渲染一个项目列表,所以无论您做什么都是正确的,并且列表的任何变化都必须重建整个列表,而不仅仅是一个项目,除非您只显示一个项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多