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

Question

Asked by Coder A on November 30, 2021 (source).

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

Answer

Question answered by 聂超群 (source).

Here is working code: enter image description here

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

FLUTTER FLUTTER-LAYOUT
SHARE: