How can I use switch statement to change listview colors
ABINASH56 opened this issue · 4 comments
here is the code .i need help in switch case. I watched this video but I need more examples to completely understand switch case..
How can i use switch case to change bg color of listview .I want to add 10 different types of colors in listview
ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Container(
color: (index % 10 == 0) ? Colors.red : Colors.green,
child: ListTile(
title: ...
),
);
},
)
Hey @ABINASH56 you can follow up with the following code .I hope this might helps you 👍
ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Container(
color: (index % 10 == 0) ? Colors.red : Colors.green,
child: ListTile(
title: Text(string),
onTap: () => setState(() => null ),
selected: null,
style: ListTileTheme(selectedColor: Colors.white,),
);
);
},
)
Also I am new to contributing , cam you please help me out to contribute further :)
Hey @ABINASH56 , have you see it
Hi @ABINASH56 I have a solution for you :
You can try this code out and see the output. This is how you can use function in dart to get Colors from switch
import 'package:flutter/material.dart';
main() {
runApp(
MaterialApp(
home: SwitchColors(),
),
);
}
class SwitchColors extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: ListView.builder(
itemCount: 5,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return Container(
color: getColor(index),
child: ListTile(
title: Text("string")
));
},
));
}
Color getColor(int index) {
switch (index) {
case 0:
return Colors.amber;
case 1:
return Colors.blue;
case 2: return Colors.green;
case 3: return Colors.grey;
case 4: return Colors.purple;
default:
return Colors.white;
}
}
}