繁体   English   中英

如何根据值更改 Flutter 中的边框颜色?

[英]How to change border color in Flutter according to the value?

我有一个带有某种颜色边框的容器小部件。 如果 TextField 中输入的值大于或小于某个值,我希望能够更改边框的颜色。 实现这一目标的最佳方法是什么?

  1. 在类中定义一个_color变量:
Color _color = Colors.purple;
  1. _color变量分配给Container的边框:
                   Container(
                      height: 100,
                      width: 100,
                      decoration: BoxDecoration(
                        border: Border.all(
                          width: 5.0,
                          // assign the color to the border color
                          color: _color,
                        ),
                      ),
                    ),
  1. TextFieldonChanged回调中测试您的条件是否满足并根据您的需要更改_color
                    TextField(
                      onChanged: (newValue) {
                        if (newValue.length > 5) { // test for your condition
                          setState(() {
                            _color = Colors.red; // change the color
                          });
                        } else {
                          setState(() {
                            _color = Colors.blue; // change the color if the condition is not met
                          });
                        }
                      },
                    ),

这是您的 TextField 控制器;

final yourTextFieldControler = TextEditingController();

只需从控制器获取值并更改为 int。

Container(
   
  decoration: BoxDecoration(
    border: Border.all(color: yourTextFieldControler.text.toInt > 5 ?  Colors.red:Colors.blueAccent)
  ),
  child: Text("My Awesome Border"),
)

这是你的 TextField

TextField(
  controler : yourTextFieldControler,
         onChanged: (newValue) {
setState((){})
}

暂无
暂无

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

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