简体   繁体   English

(Flutter/Dart) 带有列表的 If Else 语句<string>健康)状况</string>

[英](Flutter/Dart) If Else Statement with List<String> Condition

How could you help me?你怎么能帮我? How to make a condition, If Else statement with List <String'> Condition?如何使用 List <String'> 条件创建条件 If Else 语句? 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.所以,我想在 List<String'> status = 'Available' 它的颜色设置为绿色时创建一个条件,当 List<String'> status = 'Not Available' 它的颜色设置为红色时。

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)然后我将这个 function 称为我的小部件(当然使用 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我真的很感激任何答案

I recommend you to fix the types in flutter so you may better change your code like this:我建议您修复 flutter 中的类型,以便您可以更好地更改代码,如下所示:

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]))

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);
    }
  }

Like Benyamin Beyzaie showed in his answer, you missed the list indexer, when calling _getMyColor就像 Benyamin Beyzaie 在他的回答中显示的那样,您在调用 _getMyColor 时错过了列表索引器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM