You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何正确展示自定义ChangeNotifier类内存储的列表数据?

问题核心原因

  • 每次调用Collection()都会生成全新的Collection实例,你添加数据时使用的临时实例和UI中读取数据的实例完全无关,新实例的_items默认是空数组,所以不会展示内容
  • 以_开头的_items是类的私有属性,按照Dart语法规范,不能直接在类外部访问,属于语法层面的不规范用法

修复方案

1. 统一管理Collection实例

保证全局/当前业务流程内使用同一个Collection实例,可通过单例模式实现,避免每次调用都生成新实例:

class Collection with ChangeNotifier {
  // 私有构造函数,禁止外部随意新建实例
  Collection._internal();
  // 全局唯一单例对象
  static final Collection _instance = Collection._internal();
  factory Collection() => _instance;

  List<Items> _items = [];
  // 提供公开只读的get方法,避免外部直接修改内部数据
  List<Items> get items => List.unmodifiable(_items);

  void addData(Items day) {
    print(day.name);
    print(day.id);
    _items.add(day);
    print(_items);
    notifyListeners();
  }
}

class Items { 
  String name;
  String comments;
  int id;
  Items({required this.name, required this.comments, required this.id});
}

2. 修复UI层读取逻辑

配合ChangeNotifier的特性,使用Consumer监听数据变化,保证数据更新时UI自动刷新:

// 需先在父组件注册ChangeNotifierProvider,此处为列表部分的实现代码
Consumer<Collection>(
  builder: (context, collection, child) {
    return ListView.builder(
      itemCount: collection.items.length,
      itemBuilder: (BuildContext context, int index) {
        final currentItem = collection.items[index];
        print(collection.items.length);
        return Text('name ${currentItem.name} id ${currentItem.id}');
      }
    );
  }
)

3. 添加数据的逻辑保持不变

Collection().addData(Items(name: "a", comments: "sda", id: 12));

修改后添加数据和读取数据使用的是同一个实例,且UI会监听notifyListeners通知自动刷新,即可正常展示内容。

内容的提问来源于stack exchange,提问作者rameez khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 14:06:05