【问题标题】:How can I show names of fields not validate in error message on submit?如何在提交时的错误消息中显示未验证的字段名称?
【发布时间】:2022-12-21 04:17:32
【问题描述】:

当按下保存按钮时,如果表单有效,它将被成功保存,但如果无效,您将收到错误消息“请解决给定的错误”,并且在每个必填字段下都有错误消息“必填字段”。我想将未填写的必填字段的名称添加到按下保存按钮时显示的消息中(对此消息“请解决给定的错误”)。我该怎么做?

这是提交功能

 void _submit() {
if (_formKey.currentState.validate()) {
  _save();
}
else if (!_formKey.currentState.validate()) {
  _scaffoldKey.currentState.showSnackBar(
      SnackBar(
          content: Text("Please resolve given errors")
      ));
  return;
}
_formKey.currentState.save();}

这是我的 TextFormField 之一

TextFormField(
  decoration: InputDecoration(
      labelText:
      AppLocalizations.of(context)
          .getTranslated('firstName'),
      border: OutlineInputBorder(
          borderRadius:
          BorderRadius.circular(
              5.0))),
  controller: firstNameController,
  validator: (String value) {
    if (value.isEmpty) {
      return AppLocalizations.of(context)
          .getTranslated('requiredField');
    }
    return null;
  },
  onChanged: (value) {
    debugPrint(
        'Something changed in Username Text Field');
    user.firstName =
        firstNameController.text;
  },
)

【问题讨论】:

  • 您必须将验证器设置为您的TextFormField。请出示你的Textfield 我会根据你的代码举个例子
  • 好的,现在我向您展示我的 TextFormField 之一,但我已经这样做了(将验证器设置为我的 TextFormField),我想做的是在整个表单未验证时显示的消息中显示字段名称

标签: flutter validation


【解决方案1】:

声明一个字符串列表

List<String> hintList = [];

然后在 textFormField 验证器中检查值是否为空,然后将提示添加到 hintList

TextFormField(
            decoration: InputDecoration(
                labelText: "First name",
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5.0))),
            controller: firstNameController,
            validator: (value) {
              if (value == null || value.isEmpty) {
                if(!hintList.contains("First name")){
                  hintList.add("First name");
                }
                return 'Required field!';
              }
              if (hintList.contains("First name")) {
                hintList.removeWhere((element) => element == "First name");
              }
              return null;
            },
            onChanged: (value) {
              user.firstName = firstNameController.text;
            },
          )

然后按下保存按钮,放置提交功能。如果 formkey 未验证则显示提示列表为空,否则调用 save() func

void submit() {
if (formKey.currentState!.validate()) {
  save();
} else {
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text("${hintList.join(", ")} fields empty!"),
    duration: const Duration(milliseconds: 500),
  ));
}
}

【讨论】:

    【解决方案2】:

    您可以使用验证或错误文本。 我喜欢在单独的方法中使用 errorText 和验证。

    首先,创建一个验证方法:

    String? validateEmail(String? value){
        
        
        if ((value??'').isEmpty){
        setState(()=>{emailError = 'Cannot be empty'});  
        } else {
          setState(()=>{emailError = ''});  
        }
             
        return emailError;
      }
    

    所以.. 在您的 TextFormField 中放置一个错误文本。

    TextFormField(
                   style: const TextStyle(fontSize: 16.0, color: Colors.black),
                 
                  decoration: InputDecoration(                
                    errorText: (emailError != null &&( emailError??'').isEmpty )? null :emailError.toString(),
                  ),
                  controller: _myController,
                )
    

    在按钮中单击您调用验证方法。

    【讨论】:

      【解决方案3】:

      我做了一个你想要的最小例子:

      我认为您不需要 textController。

      
      class MyHomePage extends StatefulWidget {
        const MyHomePage({Key? key}) : super(key: key);
      
        @override
        State<MyHomePage> createState() => _MyHomePageState();
      }
      
      class _MyHomePageState extends State<MyHomePage> {
        final _formKey = GlobalKey<FormState>();
        final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
        Map<String, String> values = {"name": "", "age": "", "number": ""};
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            key: _scaffoldKey,
            body: Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      validator: ((value) {
                        if (value!.isEmpty) return "Required Field";
                      }),
                      onChanged: ((v) {
                        values.update("name", (value) => v);
                      }),
                    ),
                    TextFormField(
                      validator: ((value) {
                        if (value!.isEmpty) return "Required Field";
                      }),
                      onChanged: ((v) {
                        values.update("age", (value) => v);
                      }),
                    ),
                    TextFormField(
                      validator: ((value) {
                        if (value!.isEmpty) return "Required Field";
                      }),
                      onChanged: ((v) {
                        values.update("number", (value) => v);
                      }),
                    ),
                    TextButton(
                        onPressed: () {
                          _submit(values);
                        },
                        child: Text("Submit"))
                  ],
                )),
          );
        }
      
        void _submit(Map<String, String> values) {
          if (_formKey.currentState!.validate()) {
            // _save();
          } else if (!_formKey.currentState!.validate()) {
            var list =
                values.entries.where((element) => element.value.isEmpty).toList();
            if (list.length == 1) {
              _scaffoldKey.currentState!
                  .showSnackBar(SnackBar(content: Text("${list[0].key} is empty")));
            } else if (list.length == 2) {
              _scaffoldKey.currentState!.showSnackBar(SnackBar(
                  content: Text("${list[0].key} and ${list[1].key} are empty")));
            } else if (list.length == 3) {
              _scaffoldKey.currentState!.showSnackBar(SnackBar(
                  content: Text(
                      "${list[0].key},${list[1].key},and ${list[2].key} are empty")));
            }
          }
          _formKey.currentState!.save();
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-22
        • 2015-08-04
        • 1970-01-01
        • 1970-01-01
        • 2021-06-13
        • 1970-01-01
        相关资源
        最近更新 更多