0

这是代码:

if (form.validate()) {
          // Text forms was validated.
          if (mounted) {
            setState(() {
              _isButtonEnabled = true;
            });
          }
          form.save();
        }

我想为特定的 TextFormField 调用特定的验证器

4

2 回答 2

1

Joao 的回答是正确的,但它也被过度设计了。您可以改为GlobalKey为要独立验证的每个字段声明 a:

GlobalKey<FormFieldState> fieldKey = GlobalKey();

将其分配给TextFormField您要验证的:

TextFormField(
    key: fieldKey,
    ...

然后使用密钥验证该字段:

bool valid = fieldKey.currentState.validate();
于 2020-03-03T16:05:55.367 回答
0

Form您将需要使用Widget 和它自己的密钥来包装要单独验证的每个字段:

class TextFormFieldValidation extends StatefulWidget {
  @override
  _TextFormFieldValidationState createState() => _TextFormFieldValidationState();
}

class _TextFormFieldValidationState extends State<TextFormFieldValidation> {
  List<GlobalKey<FormState>> _formKeysList= [
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Form(
          key: _formKeysList[0],
          child: TextFormField(
            validator: (value) => 'Bad',
          ),
        ),
        Form(
          key: _formKeysList[1],
          child: TextFormField(
            validator: (value) => 'Bad',
          ),
        ),
        RaisedButton(
          child: Text('Validate 1'),
          onPressed: () => _formKeysList[0].currentState.validate(),
        ),
        RaisedButton(
          child: Text('Validate 2'),
          onPressed: () => _formKeysList[1].currentState.validate(),
        ),
        RaisedButton(
          child: Text('Reset'),
          onPressed: () => _formKeysList.forEach((key) => key.currentState.reset()),
        ),
      ],
    );
  }
}
于 2020-03-03T15:56:21.747 回答