How to make my backgroundColor
become dynamic color?
I have code
Expanded(
child: ListView.builder(
itemCount: controller.proposal.length,
padding: EdgeInsets.zero,
itemBuilder: (context, index) {
var item = controller.proposal[index];
if (item["status_proposal"] == "REJECTED") {
var color = Colors.red;
} else if (item["status_proposal"] == "SUBMITED") {
var color = Colors.blue;
} else {
var color = Colors.green;
}
return Card(
child: ListTile(
leading: const CircleAvatar(
backgroundColor: Colors.grey,
),
title: Text(
item["title"],
),
subtitle: Text(item["deskripsi"]),
),
);
},
),
)
How to replace Colors.grey
CircleAvatar with status_proposal
color condition?
3
Answers
Define your color variable outside the if with a default value:
Pass this to the backgroundColor
You can make a variable with the color as Ozan’s answer suggested or you can separate the logic of choosing the appropriate color in another function.
In your class add the following function:
In your expanded widget just call
getCardColor(item)
There are two issues to note here in this code:
Your
color
variable should be defined outside the if block. Otherwise the value ofcolor
that you select is only accessible within that same if block. Oman’s answer above addressed this already.Your
CircleAvatar
widget shound not be defined asconst
, otherwise you cannot set a variable value of color to it.This code should give you the result you wanted: