Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternating background colors on ListView.builder

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?

like image 214
Kevin Avatar asked Feb 06 '19 13:02

Kevin


3 Answers

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: ...
      ),
    );
  },
)
like image 132
Herohtar Avatar answered Nov 03 '22 01:11

Herohtar


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.

like image 24
Kevin Avatar answered Nov 02 '22 23:11

Kevin


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.

like image 38
JoseAA Avatar answered Nov 02 '22 23:11

JoseAA