在flutter中,我们如何在更改图标颜色或背景颜色时编写if()else if()alse()


Icon(_image == null ? MdiIcons.imageSearch : MdiIcons.checkBold,size: 35,color : _image == null ?Colors.red : Colors.blue) 

例如,上面的代码可以在蓝色和红色之间转换,但我还有两个条件需要将颜色更改为绿色和黄色

如果你真的想这样做,你可以像这个一样链接你的条件

condition1 ? Colors.red : condition2 ? Colors.blue : condition3 ? Colors.green : Colors.yellow

但是,我不推荐它。您应该将它提取到具有适当if/else语法的函数中。

我建议使用函数来选择颜色

Color getImageColor(image) {
if (image == null) {
return Colors.red;
} else if () {
... return color
} else if () {
... return color
} else {
return Colors.blue;
}
}
Icon(_image == null ? MdiIcons.imageSearch : MdiIcons.checkBold,
size: 35,
color : getImageColor(_image),
)
``

最新更新