颤振多状态管理

时间:2021-01-05 18:07:53

标签: flutter flutter-state

我有一个这样大小的盒子

    child: SizedBox(
        width: 50.0,
        height: 50.0,
        child: DecoratedBox(
          decoration: BoxDecoration(
              color: Colors.blue
          ),
        )
    ),

我想根据一个名为_status的状态的值来改变盒子装饰的颜色,_status可以有四个值1、2、3、4,并且根据状态的值我想像这样改变盒子装饰的颜色 1 - 蓝色 2 - 红色 3-琥珀色 4 - 绿色

通常使用的三元语句无济于事,因为它仅适用于有限数量的状态值,有什么方法可以实现吗?

谢谢

1 个答案:

答案 0 :(得分:2)

您可以定义辅助函数来计算颜色值

child: SizedBox(
     width: 50.0,
     height: 50.0,
     child: DecoratedBox(
       decoration: BoxDecoration(
           color: _getBoxColor(),
       ),
     )
 ),
 
//somewhere below build method
Color _getBoxColor() {
 switch (_status) {
   case 1:
     return Colors.blue;
   case 2:
     return Colors.red;
   ...
 }