首页 > 解决方案 > Flutter:验证后TextFormField丢失装饰

问题描述

我正在使用带有 InputDecorations 的 TextFormField 和一个按钮来提交文本。但是,如果字段为空并且按下按钮,则验证正常进行,但按钮失去其边框并且提示文本不会消失(输入文本覆盖在其上)。

前 后

表单域:

Center(
                  child: Container(
                    padding: EdgeInsets.only(top: ScreenHeight * 0.02),
                    width: ScreenWidth * 0.9,
                    height: ScreenHeight * 0.12,
                    child: TextFormField(
                      style: TextStyle(
                          fontSize: ScreenHeight * 0.025,
                          color: Colors.teal),
                      decoration: InputDecoration(
                        labelText: "Speciality",
                        labelStyle: TextStyle(
                            color: Colors.cyan,
                            fontSize: ScreenHeight * 0.025),
                        fillColor: Colors.white,
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                          borderSide: BorderSide(
                            color: Colors.tealAccent,
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                          borderSide: BorderSide(
                            color: Colors.cyan,
                            width: 2.0,
                          ),
                        ),
                      ),
                      validator: (String? value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter a speciality';
                        }
                        return null;
                      },
                      onChanged: (value) {
                        (_speciality = value);
                      },
                    ),
                  ),
                ),

按钮:

Center(
            child: Container(
              padding: EdgeInsets.only(
                top: ScreenHeight * 0.005,
              ),
              height: ScreenHeight * 0.06,
              child: ElevatedButton(
                onPressed: () {
               

                  if (_formKey.currentState!.validate()) {
                    // Process data.
                  }
                },
                child: const Text('Submit'),
              ),
            ),
          ),

我正在模拟器上调试代码。任何有关为什么会发生这种情况以及如何解决它的帮助将不胜感激。

标签: flutteruser-interfaceflutter-textformfield

解决方案


您应该为您的小部件提供errorBorderborder属性TextFormField

errorBorder: OutlineInputBorder(
  borderRadius: BorderRadius.circular(10.0),
  borderSide: BorderSide(
    color: Colors.cyan,
    width: 2.0,
  ),
),
border: OutlineInputBorder(
  borderRadius: BorderRadius.circular(10.0),
  borderSide: BorderSide(
    color: Colors.cyan,
    width: 2.0,
  ),
),

推荐阅读