【问题标题】:How can I add text per generated item in ListView of Flutter?如何在 Flutter 的 ListView 中为每个生成的项目添加文本?
【发布时间】:2021-11-14 21:37:13
【问题描述】:

我有这个代码,它给了我一个项目列表。

我想: 1 - 使项目可点击(可能通过手势检测) 2 - 允许文本 + 图标可以更改并且每个项目都不同。现在,我可以为所有项目显示相同的文本(因为这一行:child: new Text("$index"),),但它们需要不同,这样我才能真正实现以下目标:

Container(
    height: 80.0,
    child: new ListView(
      scrollDirection: Axis.horizontal,
      children: new List.generate(10, (int index) {
        return new Card(
          color: Colors.blue[index * 100],
          child: new Container(
            width: 50.0,
            height: 50.0,
            child: new Text("$index"),
          ),
        );
      }),
    ),
  ),

这应该是最终结果:

我将整理手势和点击,但我如何创建它,以便我可以为每个生成的项目以不同的方式命名我的项目?

【问题讨论】:

  • 不同如何?您要实现的逻辑是什么?您缺少数据。
  • 如手动(类别等)。

标签: flutter dart filter flutter-layout


【解决方案1】:

首先添加您要创建的模型,我们以类别为例, 模型将是这样的:

class Category {
  String id;
  String name;
  String icon; // or image, anything you want
}

然后,从服务器或手动填充数据,如下所示:

final categories = <Category>[
  Category("1", "American", /** Icons.food or url to icon*/);
  Category("2", "other", /** Icons.food or url to icon*/);
];

现在您有了数据,用ListView.builder 显示它,将如下所示:

ListView.builder(
  padding: const EdgeInsets.all(8),
  itemCount: categories.length,
  itemBuilder: (BuildContext context, int index) {
    return Card(
          color: Colors.blue[index * 100],
          child: new Container(
            width: 50.0,
            height: 50.0,
            child: new Text(categories[index].name), // same with icon
          ),
        );
  }
);

【讨论】:

  • 我必须把 final categories = [ 放在类 Category 中吗?因为它是说'期望找到];。
  • 缺少一个分号,添加即可
猜你喜欢
  • 2020-06-27
  • 2020-12-06
  • 2021-02-19
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 2020-11-18
相关资源
最近更新 更多