Issue
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.
Solution
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()),
),
),
),
);
}
}
Answered By - littleironical
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.