Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter : How to change listtile color in ListView Builder , from list of colors. Even list of colors size is less than items

Suppose list of colors are ,

List colors = [Colors.red, Colors.yellow,Colors.blue, Colors.green]; //4 colors and items are more than 4 , how do I repeat these colors for next items.

pic

Expected result,

item1 - red, item2 - yellow, item3 - blue, item4 - green, item5 - red, item6 - yellow, item7 - blue, item8 - green,

pic2

Full Code

  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")
              );
          }
          );
    }
  }
like image 299
Coder Addy Avatar asked Dec 09 '25 04:12

Coder Addy


2 Answers

Here is working code: enter image description here

If you want a infinite list, set itemCount to null :)

like image 129
聂超群 Avatar answered Dec 11 '25 23:12

聂超群


Add a variable that you can reference for the index from the color list.

int i = 0;

Then, on your ListView.builder builder function, check if you reached the end of the list.

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")
   );
   
   }
 )

I do not know if this is efficient but you get the idea.

like image 28
Pol Avatar answered Dec 11 '25 21:12

Pol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!