I have a ListView.builder generating ListTiles from a List. I would like to achieve an alternating color like you would a typical list.

Is there a Flutter official way to do this? Or I'm stuck with doing something like

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"),
          ],),
      ),

or something to that effect?


Solution 1: Kevin

Got it.

Instead of using ListTile I can use a Card to have the color property accessible. Then with @pskink's suggestion, I can use the index to determine whether it's odd or even.


Solution 2: Herohtar

You can use the index provided to the item builder to set the color, and if you want to use a ListTile you can easily give it a background color by wrapping it in a Container:

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


Solution 3: Jose G

The way I did it is by setting up my list then creating a method where the return type is Color and the parameter passed in is the index.

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

In the Color named parameter call selectedColour and you'll have colours alternate the way you'd want.