简体   繁体   English

如何在 listviewbuilder 的 textformfield 中添加验证?

[英]How can I add validation in textformfield in listviewbuilder?

I am creating a dynamic textformfield using Listviewbuilder :-我正在使用 Listviewbuilder 创建动态文本表单字段:-

(1). (1). I want to add validation in mobile field (2).我想在移动字段 (2) 中添加验证。 I want to add validation in name field我想在名称字段中添加验证

But in dynamic condition my validation is not working properly.但在动态条件下,我的验证无法正常工作。

First store your fields validation in a Map like below.首先将您的字段验证存储在如下地图中。

Map contains 'key' as fields name and 'values' as validator functions. Map 包含“key”作为字段名称和“values”作为验证器函数。

 Map<String, String? Function(String?)?> formFields = { 'username': (String? value) { return (value!.isEmpty) ? 'Can not be Empty' : null; }, 'password': (String? value) { return (value == null || value!.length < 8) ? 'Must be 8 Char Long' : null; }, };

Use the Map key to access validator functions.使用 Map 键访问验证器功能。

formFields[formFields.keys.elementAt(index)] formFields[formFields.keys.elementAt(index)]

And then use ListView.builder to generate multiple TextFormFields like below.然后使用 ListView.builder 生成多个 TextFormField,如下所示。

 ListView.builder( itemCount: formFields.length, itemBuilder: (context, index) { return TextFormField( decoration: InputDecoration( labelText: formFields.keys.elementAt( index), // this gives key String ('username', 'password') ), onSaved: (String? value) {}, validator: formFields[formFields.keys.elementAt(index)], ); }, ),

For different type of Form Elements lets say TextFormField, DropdownButtonFormField you could directly add these widgets on the MAP instead of Validator only.对于不同类型的表单元素,例如 TextFormField、DropdownButtonFormField,您可以直接在 MAP 上添加这些小部件,而不仅仅是 Validator。

 Map<String, String? Function(String?)?> formFields = { 'username': TextFormField( decoration: InputDecoration( labelText: formFields.keys.elementAt( index), // this gives key String ('username', 'password') ), onSaved: (String? value) {}, validator: TextFormField( decoration: InputDecoration( labelText: formFields.keys.elementAt( index), // this gives key String ('username', 'password') ), onSaved: (String? value) {}, validator: (String? value) { return (value!.isEmpty) ? 'Can not be Empty' : null; }, );, );, );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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