Michael Knight
Michael Knight

Reputation: 39

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?

Upvotes: 1

Views: 7218

Answers (2)

Deepak Ror
Deepak Ror

Reputation: 2234

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((){})
}

Upvotes: 0

timilehinjegede
timilehinjegede

Reputation: 14033

  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
                          });
                        }
                      },
                    ),

Upvotes: 4

Related Questions