【问题标题】:Flutter : How to change listtile color in ListView Builder , from list of colors. Even list of colors size is less than itemsFlutter:如何从颜色列表中更改 ListView Builder 中的 listtile 颜色。甚至颜色表尺寸小于项目
【发布时间】:2021-11-30 05:40:04
【问题描述】:

假设颜色列表是 ,

列表颜色 = [Colors.red, Colors.yellow,Colors.blue, Colors.green]; //4种颜色 并且项目超过 4 ,我如何为下一个项目重复这些颜色。

预期结果,

item1 - 红色, item2 - 黄色, item3 - 蓝色, item4 - 绿色, item5 - 红色, item6 - 黄色, item7 - 蓝色, item8 - 绿色,

完整代码

  import 'package:flutter/material.dart';


  void main() {
    runApp(MyApp());
  }

  List colors = [Colors.red, Colors.yellow,Colors.blue, Colors.green];

  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          body: Center(
            child: MyWidget(),
          ),
        ),
      );
    }
  }

  class MyWidget extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return ListView.builder(
          itemCount: 8,
          itemBuilder: (BuildContext context,int index){
            return ListTile(
                tileColor: colors[index] ,
              
              title:Text("List item $index")
              );
          }
          );
    }
  }

【问题讨论】:

    标签: flutter flutter-layout


    【解决方案1】:

    这是工作代码:

    如果您想要一个无限列表,请将 itemCount 设置为 null :)

    【讨论】:

      【解决方案2】:

      为颜色列表中的索引添加一个变量。

      int i = 0;
      

      然后,在您的 ListView.builder 构建器函数中,检查您是否到达列表末尾。

      ListView.builder(
         itemCount: 8,
         itemBuilder: (BuildContext context,int index){
      
         if (i > colors.length) i = 0;
      
         final color = colors[i];
         i++;
         return ListTile(
           tileColor: color, 
           title:Text("List item $index")
         );
         
         }
       )
      

      我不知道这是否有效,但你明白了。

      【讨论】:

      • 最终颜色 = 颜色[index % colors.length]
      【解决方案3】:

      您可以调整颜色数组的大小:

      colorsArray.removeRange(itemNameList.length, colorsArray.length);
            
      

      【讨论】:

        猜你喜欢
        • 2019-12-08
        • 2020-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-05
        • 1970-01-01
        • 2011-10-17
        相关资源
        最近更新 更多