How to set different background color to each ListView items in flutter
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.
dartKnightRises
Updated on December 22, 2022Comments
-
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 almost 4 yearsHow 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 almost 4 yearsYa some kind of gradient.
-
dartKnightRises almost 4 yearsI want to calculate it through Index. Do I need to define some kind of array?
-
Christopher Moore almost 4 yearsIt 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 almost 4 yearsOkay I will read ColorTween, No I don't know the number of elements.
-
Christopher Moore almost 4 yearsAssuming you know what colors the beginning and end of the
ListView
should be, this should be a good application ofColorTween
. -
dartKnightRises almost 4 yearsIf it would be not complicated, can you share a small snippet of code or else I will go through it.
-
Christopher Moore almost 4 yearsYeah I could. Could you provide me with an initial and ending color? Is this an infinite list?
-
dartKnightRises almost 4 yearsAmberAccent to OrangeAccent.
-
Christopher Moore almost 4 yearsLet us continue this discussion in chat.
-
-
dartKnightRises almost 4 yearsHey @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 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 almost 4 yearsI've edited my code to generate random colors. You can check it now