0

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

  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;
  }
4

2 回答 2

1

也许函数返回类型应该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;
  }

在 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,
    );
  }
}

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,
    );
  }
}

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

于 2021-06-15T20:40:43.563 回答
0

添加 String 作为checkFieldEmpty()方法的返回类型,见下文

取而代之的是:

checkFieldEmpty(String fieldContent) {}

用这个:

String checkFieldEmpty(String fieldContent) {}

完整代码示例:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(title: Text(appTitle)),
        body: MyCustomForm(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();

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

  String checkFieldEmpty(String fieldContent) {
    if (fieldContent.isEmpty) return 'Ce champ est obligatoire.';
    return null;
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          textField('changedValue', 'Enter Password', false),
          ElevatedButton(
            onPressed: () {
              // Validate returns true if the form is valid, or false otherwise.
              if (_formKey.currentState.validate()) {
                // If the form is valid,
                // perform further actions here
              }
            },
            child: Text('Submit'),
          ),
        ],
      ),
    );
  }
}
于 2021-06-15T20:54:04.027 回答