Home > Software engineering >  (Flutter/Dart) If Else Statement with List<String> Condition
(Flutter/Dart) If Else Statement with List<String> Condition

Time:11-23

How could you help me? How to make a condition, If Else statement with List <String'> Condition? I have tried many things that probably could solved my trouble. But i still get stucked.

so, i want to make a condition when the List<String'> status = 'Available' it's color set to green, and when the List<String'> status = 'Not Available' it's color gonna set to red.

here's my code :

List<String> status = ['Available','Not Available','Available','Available','Not Available'];

_getMyColor(status){
   if(status == "Available"){
     return Color(0x00FF00);
   } else {
     return Color(0xFF0000);
   }
}

And then i call this function into my widget (of course with ListView.builder)

Text(status[index]), style: TextStyle(color: _getMyColor(status))

The code isn't got error message, but it makes my Text widget disappear.

I really appreciate any answers

CodePudding user response:

I recommend you to fix the types in flutter so you may better change your code like this:

List<String> status = ['Available','Not Available','Available','Available','Not Available'];

Color _getMyColor(String status){
   if(status == "Available"){
     return Color(0x00FF00);
   } else {
     return Color(0xFF0000);
   }
}

and you can simply use this like this:

Text(status[index]), style: TextStyle(color: _getMyColor(status[index]))

CodePudding user response:

For a better structure use enum:

enum MyStatus{
  available, notAvailable
}

then

  Color _getMyColor(MyStatus status){
    switch(status){
      case MyStatus.available:
        return const Color(0x0000ff00);
      case MyStatus.notAvailable:
        return const Color(0x00ff0000);
    }
  }

CodePudding user response:

Like Benyamin Beyzaie showed in his answer, you missed the list indexer, when calling _getMyColor

...(color: _getMyColor(status[index]))
  • Related