Kevin
Kevin

Reputation: 341

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?

Upvotes: 9

Views: 13465

Answers (4)

Mohamed Hammane
Mohamed Hammane

Reputation: 151

You can do something like :

@override
Widget build(BuildContext context) {
  Color? color;
  ...
  itemBuilder: (BuildContext context, int index) {

            var value = list[index];
            if(index > 0){
              var preValue= list[index-1];
              if(preValue != value) color = color == null ? const Color.fromRGBO(0, 0, 250, 0.1) : null;
            }

  ...

Upvotes: 0

Jose G
Jose G

Reputation: 21

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.

Upvotes: 2

Herohtar
Herohtar

Reputation: 5613

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: ...
      ),
    );
  },
)

Upvotes: 28

Kevin
Kevin

Reputation: 341

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.

Upvotes: 3

Related Questions