I have an API and get the data from them.
Actually, I want to change the box color if any string exists in query.
Currently, I check if the last one is.
The code I use:
border: Border(
left: BorderSide(
color: model.data[model.data.length - 1].desc ==
'DONE'
? greenColor
: redColor,
width: 3.0)),
The border is green only if the DONE
word exist in last value in query, but if exist but not in last the border is red.
In certain cases it can be in the penultimate place or somewhere in the middle. It is not always the last. To check if the word DONE
exists in JSON query regardless of where it is in the sequence.
The JSON:
[
{
"id":"123",
"title":"Alpha",
"desc":"NEW"
},
{
"id":"123",
"title":"Alpha",
"desc":"DONE"
},
{
"id":"123",
"title":"Alpha",
"desc":"IN PROGRESS"
}
]
Did you need more info to give me a solution?
Thanks.
CodePudding user response:
- indexWhere can solve it
- example
model.data.indexWhere((m) => m.desc == 'DONE')? greenColor : redColor
CodePudding user response:
You can archive this many ways
Color borderColor = Colors.red;
//1st way
final index = response.indexWhere((element) => element.desc == "DONE"); // Return -1 If 'DONE' is not found
debugPrint("index of Done $index");
borderColor = index != -1 ? Colors.green : Colors.red;
//2nd way
final isDone = response.map((e) => e.desc == "DONE").toList().isNotEmpty; // Return false If 'DONE' is not found
debugPrint("If Done exists $isDone");
borderColor = isDone ? Colors.green : Colors.red;