简体   繁体   English

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

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

I have a container widget with a border of a certain color.我有一个带有某种颜色边框的容器小部件。 I want to be able to change the color of the border if the entered value in a TextField is greater or less than some value.如果 TextField 中输入的值大于或小于某个值,我希望能够更改边框的颜色。 What would be the best way to acheive this?实现这一目标的最佳方法是什么?

  1. Define a _color variable in your class:在类中定义一个_color变量:
Color _color = Colors.purple;
  1. Assign the _color variable to the Container 's border:_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. Test if your condition is met in the onChanged callback of the TextField and change the _color according to your needs: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
                          });
                        }
                      },
                    ),

This is your TextField COntroller;这是您的 TextField 控制器;

final yourTextFieldControler = TextEditingController();

Just getValue From controller and change to int.只需从控制器获取值并更改为 int。

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

This is your TextField这是你的 TextField

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

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

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