skip to Main Content

In my below code there is a custom container named GunasoContainer which has 2 custom text widgets gunasoNum, status and these text widgets’s data is populated from api response, in status widget there can be one of 3 response ‘Solved’ or ‘Declined’ or ‘pending’, now I want to chnage the color of texts inside status widget based on type of response, for example: if status has response ‘Solved’ the font color should be green, and if status has response ‘Declined’ the font color should be red , if status has response ‘pending’ the font color should be yellow. now, how to add if, else-if and else condition in flutter custom widgets?

 GunasoContainer(

gunasoNum: response .response[index].grievance_no,
 status: response.response[index].status,
fontColor: response.response[index].status ==   'Solved'  ? Colors.white : Colors.deepOrange,  ),

2

Answers


  1. There are essentially two different methods that I use to solve issues like this and quite honestly it comes down to personal preference. You can either create a function and pass the variable, in this case response, and then return a color from that function or you can use the conditional operator ?.

    Example with function, my personal go-to:

    Color getGuanasoColor(String responseStatus) {
        switch (responseStatus) {
          case 'Solved':
            return Colors.green;
          case 'Declined':
            return Colors.red;
          case 'Pending':
            return Colors.yellow;
        }
      }
    GunasoContainer(
      gunasoNum: response .response[index].grievance_no,
      status: response.response[index].status,
      fontColor: getGuanasoColor(response.response[index].status),
    ),
    

    You had the conditional operator started, you just have to continue:

    // This assumes that there are only three possible status states
    fontColor: response.response[index].status == 'Solved' ? Colors.green : response.response[index].status == 'Declined' ? Colors.red : Colors.yellow,
    
    Login or Signup to reply.
  2. If you want to change color u can do this way

    GunasoContainer(
     gunasoNum: response .response[index].grievance_no,
     status: response.response[index].status,
     fontColor: response.response[index].status ==   'Solved'  ? Colors.white 
              : response.response[index].status ==   'Declined'? Colors.red
              : Colors.yellow,  ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search