首页 > 解决方案 > Flutter 多状态管理

问题描述

我有一个像这样大小的盒子

    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 - 绿色

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

谢谢

标签: flutterflutter-state

解决方案


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

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

推荐阅读