【问题标题】:Alternating background colors on ListView.builderListView.builder 上的交替背景颜色
【发布时间】:2019-06-30 10:53:36
【问题描述】:

我有一个 ListView.builder 从列表生成 ListTiles。我想像典型列表一样实现交替颜色。

有 Flutter 官方的方法来做到这一点吗?或者我坚持做类似的事情

ListView.builder(
...
  itemBuilder: (...) {
    return ListTile
      ..
      title: Container(
        decoration: BoxDecoration(color: Colors.grey),
          child: Column(children: <Widget>[
            Text("What should've been the title property"),
            Text("and its trailing"),
          ],),
      ),

或类似的东西?

【问题讨论】:

  • 你有一个 index 传递给 itemBuilder - 使用它
  • @pskink 我想得到一个关于如何设计样式的答案,特别是,谢谢。我可以使用索引来确定它是奇数还是偶数。

标签: dart flutter widget


【解决方案1】:

您可以使用提供给项目构建器的index 来设置颜色,如果您想使用ListTile,您可以通过将其包裹在Container 中轻松为其赋予背景颜色:

ListView.builder(
  itemBuilder: (BuildContext context, int index) {
    return Container(
      color: (index % 2 == 0) ? Colors.red : Colors.green,
      child: ListTile(
        title: ...
      ),
    );
  },
)

【讨论】:

  • 如何添加更多颜色。我有 10 个列表,我想添加 10 种不同的颜色,我该如何实现这一目标
  • 尝试将逻辑更改为index % 10 并使用switch 语句。
  • 小记,但可以使用index.isEven
【解决方案2】:

知道了。

我可以使用Card 代替ListTile 来访问color 属性。然后根据@pskink 的建议,我可以使用索引来确定它是奇数还是偶数。

【讨论】:

  • 您也可以将ListTile 包裹在Container 中并设置其颜色。
【解决方案3】:

我这样做的方法是设置我的列表,然后创建一个方法,其中返回类型是颜色,传入的参数是索引。

Color selectedColour(int position) {
  Color c;
  if (position % 3 == 0) c = Colours.cTLightBlue;
  if (position % 3 == 1) c = Colours.cTMidBlue;
  if (position % 3 == 2) c = Colours.cTDarkBlue;
  return c;
}

在名为“颜色”的参数调用 selectedColour 中,您将按照您想要的方式交替显示颜色。

【讨论】:

    猜你喜欢
    • 2011-10-13
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    相关资源
    最近更新 更多