具有值时更改TextField的颜色边框

时间:2020-08-05 17:35:01

标签: flutter

我下面有一个TextField代码。

                 TextField(
                    ...
                    controller: controller,
                    decoration: InputDecoration(
                      enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.white)),
                      //change to blue
                      focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.red, width: 5)),
                      hintText: '',
                    ),
                    keyboardType: TextInputType.number,
                    onChanged: (text) {
                      if (text != "") {
                       //change 'borderSide' from 'Colors.white' to 'Colors.blue'
                      } 
                    },
                  ),
                ),
                Container(
                    ...
                    color: Colors.red, 
                    //change to blue
                 ),

当用户键入一个值时,TextField的边框将更改颜色样式。

我想将borderSide的边界TextFieldColors.white更改为Colors.bluecolor的值为Container时,将Colors.red中的Colors.blueTextField(text != "")

我该怎么做?

1 个答案:

答案 0 :(得分:3)

您可以在主窗口小部件的状态中添加变量color,以容纳Container的颜色和TextField的边框:

Color _color = Colors.red;

然后,您可以在更改文本(onChanged)时切换其值:

TextField(
                    controller: controller,
                    decoration: InputDecoration(
                      enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.white)),
                      focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: _color, width: 5)),
                      hintText: '',
                    ),
                    keyboardType: TextInputType.number,
                    onChanged: (text) {
                      setState(() {
                        if (text.length > 0) {
                          _color = Colors.blue;
                        } else {
                          _color = Colors.red;
                        }
                      });
                    },
                  ),
                ),
                Container(height: 300, color: _color),