如何在 TextFormField 中传递函数作为验证器?

gab*_*har 6 validation dart flutter textformfield

我想知道是否可以传递一个函数作为验证器。我尝试过,但没有结果。

  Widget Field(String changedValue, String label, bool isTextObscured) {
    return TextFormField(
      decoration: InputDecoration(labelText: label),
      validator: checkFieldEmpty,
    );
  }

  checkFieldEmpty(String fieldContent) {
    if(fieldContent.isEmpty) {
      return 'Ce champ est obligatoire.';
    }
    return null;
  }
Run Code Online (Sandbox Code Playgroud)

You*_*MOU 12

也许函数返回类型应该String?适合验证器原型!

  Widget Field(String changedValue, String label, bool isTextObscured) {
    return TextFormField(
      decoration: InputDecoration(labelText: label),
      validator: checkFieldEmpty,
    );
  }

 String? checkFieldEmpty(String? fieldContent) { //<-- add String? as a return type
    if(fieldContent.isEmpty) {
      return 'Ce champ est obligatoire.';
    }
    return null;
  }
Run Code Online (Sandbox Code Playgroud)

在 Flutter 中执行此操作的更合适方法

请记住,flutter 是一种声明性语言。也就是说,您通过构建小部件树来构建应用程序。在这里,您使用一个函数来返回一个小部件。这就是违反了这条规则。相反,您应该声明自己的自定义小部件来实现该TextField小部件。就是这样:

1. 声明您的自定义小部件

// Declare your CustomTextField as a Stateless/Stateful Widget
class MyCustomTextField extends StatelessWidget {
  // Declare your custom vars, including your validator function
  final String? changedValue; 
  final String? label; 
  final bool? isTextObscured;
  final String? Function(String?)? validator;

  const MyCustomTextField({
    Key? key, 
    this.changedValue, 
    this.label,
    this.isTextObscured,
    this.validator,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(labelText: label),
      validator: validator,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

2. 使用您的自定义小部件

现在您可以将此自定义小部件用作任何其他小部件的子项:

class ParentWidget extends StatelessWidget {
  const ParentWidget({Key? key}) : super(key: key);

  // This is your custom validator function and can leave
  // anywhere ;)
  Stirng? customValidtaor(String? fieldContent) => fieldContent.isEmpty? 'Ce champ est obligatoire.': null

  @override
  Widget build(BuildContext context) {
    return MyCustomTextField(
      label: 'Some label'
      // declare the validator here...
      // valiator: (fieldContent) => fieldContent.isEmpty? 'Ce champ est obligatoire.': null
      // or use your custom validator function
      validator: customValidator,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

通过这样做,您就尊重了 Flutter 使用 Widget 组合的最佳实践;)