How to set different background color to each ListView items in flutter

2,696

Solution 1

If you want to generate random colors, then use this:

import 'dart:math';

color: Colors.primaries[Random().nextInt(Colors.primaries.length)],

If you have known number of items in the list, you can have a list of the colors you want:

class PageTwoState extends State<PageTwo> {

  //ADDED
  var colors = [
    Colors.red,
    Colors.blue,
    Colors.cyan,
    Colors.green,
    Colors.yellow,
  ];

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemExtent: 250.0,
      itemCount: 5,//CHANGED
      itemBuilder: (context, index) => Container(
        padding: EdgeInsets.all(10.0),
        child: Material(
          elevation: 4.0,
          borderRadius: BorderRadius.circular(5.0),
          color: colors[index],//CHANGED
          child: Center(
            child: Text(index.toString()),
          ),
        ),
      ),
    );
  }
}

Solution 2

The following is an example that uses ColorTween to create a gradient with consistent beginning and ending colors.

class PageTwoState extends State<PageTwo> {
  ColorTween color = ColorTween(begin: Colors.amberAccent, end: Colors.orangeAccent);
  
  @override
  Widget build(BuildContext context) {
    int listLen = 15; //Input the length of the list you retrieve from firebase here
    //The gradient will adjust for variations in length by itself as your database changes.
    
    return ListView.builder(
      itemCount: listLen,
      itemExtent: 250.0,
      itemBuilder: (context, index) => Container(
            padding: EdgeInsets.all(10.0),
            child: Material(
              elevation: 4.0,
              borderRadius: BorderRadius.circular(5.0),
              color: color.lerp(index/(listLen-1)),
              child: Center(
                child: Text(index.toString()),
              ),
            ),
          ),
    );
  }
}

This will only work with a ListView with a finite length. But it seems you are retrieving a finite List of elements to show from firebase, so this should work out just fine for you. You just have to tell the builder how many elements the List you want to show has.

Solution 3

void main() {
  final myList = [1, 2];

  for (var i = 0; i < 5; i++) {
    print(myList[i % myList.length]);
  }
}

result

1
2
1
2
1

ListView will work same way

 final _colors = [
    Colors.blue.withOpacity(0.1),
    Colors.red.withOpacity(0.1),
    Colors.yellow.withOpacity(0.1),
    Colors.green.withOpacity(0.1),
  ];

 @override
  Widget build(BuildContext context) {
    return ListView.builder(
          itemCount: data.length,
          itemBuilder: (context, index) {
            return Card(
              color: _colors[index % _colors.length]
              child: ListTile(),
            );
          },
        );

Solution 4

An option would be to generate random colors and save them in a list to check if they are already used by one of your element. Here is a way of doing so:

List<Color> _alreadyUsedColors = [];

Color _randomColor() {
   Color newColor = Color((math.Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0);
   while (_alreadyUsedColors.contains(newColor))
      newColor = Color((math.Random().nextDouble() * 0xFFFFFF).toInt())
          .withOpacity(1.0);
   _alreadyUsedColors.add(newColor);
   return newColor;
}

// Then use it like this in your widget
Material(
   elevation: 4.0,
   borderRadius: BorderRadius.circular(5.0),
   color: _randomColor(),
   child: Center(child: Text(index.toString())),
)

You add to your _alreadyUsedColors each new color generated to ensure they are used only once and the _randomColor method will return the color to your Material widget.

Share:
2,696
dartKnightRises
Author by

dartKnightRises

Updated on December 22, 2022

Comments

  • dartKnightRises
    dartKnightRises over 1 year

    I've been gone through many tutorials and I'm only able to switch between two colors by checking whether the index is even or odd.

    Here is my Code:

    class PageTwoState extends State<PageTwo> {
      @override
      Widget build(BuildContext context) {
        return ListView.builder(
          itemExtent: 250.0,
          itemBuilder: (context, index) => Container(
                padding: EdgeInsets.all(10.0),
                child: Material(
                  elevation: 4.0,
                  borderRadius: BorderRadius.circular(5.0),
                  color: index % 2 == 0 ? Colors.cyan : Colors.deepOrange,
                  child: Center(
                    child: Text(index.toString()),
                  ),
                ),
              ),
        );
      }
    }
    

    I want each item to have a different background color(suppose if I have 10 items in my list then I want each item to have a different background color.), but by using a ternary operation I'm not able to do that.

    • Christopher Moore
      Christopher Moore almost 4 years
      How to want to get the color? Do you want it to be random or some kind of gradient? How do you expect to calculate a color from an index?
    • dartKnightRises
      dartKnightRises almost 4 years
      Ya some kind of gradient.
    • dartKnightRises
      dartKnightRises almost 4 years
      I want to calculate it through Index. Do I need to define some kind of array?
    • Christopher Moore
      Christopher Moore almost 4 years
      It really depends on your application. You could predefine an array if you know the number of elements beforehand or you can use a ColorTween to dynamically create a gradient with a list of variable length.
    • dartKnightRises
      dartKnightRises almost 4 years
      Okay I will read ColorTween, No I don't know the number of elements.
    • Christopher Moore
      Christopher Moore almost 4 years
      Assuming you know what colors the beginning and end of the ListView should be, this should be a good application of ColorTween.
    • dartKnightRises
      dartKnightRises almost 4 years
      If it would be not complicated, can you share a small snippet of code or else I will go through it.
    • Christopher Moore
      Christopher Moore almost 4 years
      Yeah I could. Could you provide me with an initial and ending color? Is this an infinite list?
    • dartKnightRises
      dartKnightRises almost 4 years
      AmberAccent to OrangeAccent.
    • Christopher Moore
      Christopher Moore almost 4 years
  • dartKnightRises
    dartKnightRises almost 4 years
    Hey @Hardik Kumar, Actually I'm not sure about the number of elements in my list,sometimes it goes more than hundred and sometimes only 2-3 elements.
  • Anurag Tripathi
    Anurag Tripathi almost 4 years
    @PraveenGupta you can put modulus of the index to get color from Colors like this : colors[index % 5] that should solve your problem
  • littleironical
    littleironical almost 4 years
    I've edited my code to generate random colors. You can check it now