【问题标题】:Is there any way to alternate the backgroundColor of leading, CircleAvatar有什么办法可以改变前导的背景颜色,CircleAvatar
【发布时间】:2021-10-18 08:09:26
【问题描述】:

我正在将 api 响应的数据显示到 ListView.builder、ListTile 中,我想替换 CircleAvatar 的背景颜色,假设 api 响应数据长度为 5,那么在第 1 和第 2 圆中头像背景颜色将相同到第 4 和第 5(如果有 3 种替代颜色)

 ListTile(
    leading:  CircleAvatar(
    radius: 25,
 backgroundColor:Colors.red

请帮忙解决这个问题?

【问题讨论】:

    标签: flutter android-listview background-color


    【解决方案1】:

    试试这个:

    int i = 0;
    
    ListView(...
    
     Color c = Colors.red;
    
     if(i == 0) i++;
     else if(i == 1) {
       c = Colors.blue;
       i++;
     } else if(i == 2) {
       c = Colors.yellow;
       i = 0;
     }
    
     ListTile(
        leading:  CircleAvatar(
        radius: 25,
     backgroundColor: c
    

    【讨论】:

      【解决方案2】:

      1,2 和 4,5 的交替逻辑对我来说有点令人困惑,但据我了解,您可以使用构建器索引来更改颜色。像这样的:

      ListView.builder(
      itemCount: dummyList.length,
      itemBuilder: (context, index) => ListTile(
          leading:  CircleAvatar(
              radius: 25,
              backgroundColor: [1,2,4,5].contains(index) ? Colors.red : Colors.blue
              ),
          ),
      ); 
      

      您可能需要根据需要更改逻辑。例如,只有最后两个的颜色是:

      [dummyList.length - 1, dummyList.length].contains(index) ? Colors.red : Colors.blue
      

      或者只有偶数是

      (index % 2) == 0 ? Colors.red : Colors.blue
      

      【讨论】:

        【解决方案3】:

        试试下面的代码,希望它可以帮助你改变你需要的值和颜色,比如 0 和 1:

        //declare one varibale 
        var lead;
        
        backgroundColor: (lead == '0')? Colors.blue: (lead == '1')? Colors.red: Colors.green,
        

        【讨论】:

          猜你喜欢
          • 2020-12-10
          • 1970-01-01
          • 2020-02-27
          • 2011-02-12
          • 1970-01-01
          • 2012-02-19
          • 1970-01-01
          • 1970-01-01
          • 2019-09-12
          相关资源
          最近更新 更多