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

如何使用Bloc配合ListView.builder展示列表条目(而非长度)

解决方案

你现在的问题是每次都输出了列表的总长度,要展示具体条目,得先拿到当前索引对应的Food对象,再访问它的属性。

修改步骤:

  • 在itemBuilder里先获取当前条目的对象:final foodItem = state.Food[index];
  • 把Text的内容替换成该对象的具体属性(比如名称、描述,根据你的Food模型字段调整)

修改后的代码:

child: ListView.builder(
  itemCount: state.Food.length,
  itemBuilder: (context, index) {
    // 获取当前索引对应的Food条目
    final foodItem = state.Food[index];
    return Row(
      children: [
        const SizedBox(
          height: 10,
          width: 10,
          child: CircleAvatar(
            foregroundColor: ColorName.brandSecondaryGreen,
            backgroundColor: ColorName.brandSecondaryGreen,
          ),
        ),
        const SizedBox(width: 5),
        Text(
          // 替换成你要展示的具体属性,比如foodItem.name、foodItem.description等
          foodItem.name, 
          style: subtitle1(),
        ),
      ],
    );
  },
);

注意:foodItem.name只是示例,你需要根据自己定义的Food类的实际字段来写,比如如果字段叫title就用foodItem.title,确保字段名称和你的模型一致。

内容的提问来源于stack exchange,提问作者Bilbo Baggins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 00:45:35