skip to Main Content

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.

2

Answers


  1. You can archive this many ways

    Color borderColor = Colors.red;
    
    //1st way 
    final index = model.data.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 = model.data.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;
    
    Put line in your code
    

    model.data.indexWhere((element) => element.desc == "DONE") ?
    greenColor : redColor

    Login or Signup to reply.
    • indexWhere can solve it
    • example
     model.data.indexWhere((m) => m.desc == 'DONE')? greenColor : redColor
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search