简体   繁体   中英

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. What would be the best way to acheive this?

  1. Define a _color variable in your class:
Color _color = Colors.purple;
  1. Assign the _color variable to the Container 's border:
                   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:
                    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;

final yourTextFieldControler = TextEditingController();

Just getValue From controller and change to 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(
  controler : yourTextFieldControler,
         onChanged: (newValue) {
setState((){})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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