Flutter自动表单生成插件autoform的使用

发布于 1周前 作者 bupafengyu 来自 Flutter

Flutter 自动表单生成插件 autoform 的使用

autoform 是一个简单的包,可以帮助你构建表单。本文将介绍如何使用 autoform 插件来快速创建和验证表单。

开始使用

autoform 提供了一个简单的方式来构建表单。以下是一个基本的实现示例:

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  // 定义一个表单实例
  var form = AutoForm(
    values: {'name': 'Edwards'}, // 初始值
    properties: [
      AutoProperty(
        field: 'name',
        title: '姓名', // 表单字段的标题
        validator: AutoValidators.isEmail, // 验证器
        type: AutoPropertyType.text, // 字段类型
      ),
      AutoProperty(
          field: 'personality',
          title: '人格类型', // 表单字段的标题
          validator: AutoValidators.isEmail, // 验证器
          type: AutoPropertyType.multiselect, // 字段类型
          options: ['简单', '复杂', '其他']), // 多选选项
    ],
  ).create(); // 创建表单实例

  @override
  void initState() {
    super.initState();
    var s = AutoFormSettings();
    s.fieldMargin = EdgeInsets.symmetric(vertical: 20); // 设置字段间距
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
          children: [
            form.widget, // 渲染表单
            ElevatedButton(
              onPressed: () {
                var isValid = form.form.validate(); // 验证表单
                if (isValid) {
                  pprint("表单验证成功"); // 如果验证成功
                } else {
                  pprint("表单有错误"); // 如果验证失败
                }
              },
              child: Text("验证"), // 按钮文本
            ),
          ],
        ),
      ),
    );
  }
}

从 Map 创建表单

除了手动定义表单外,你还可以从 Map 中创建表单。这使得你可以动态地定义表单结构。

var personForm = AutoForm.fromMap({
  'properties': [
    {
      'title': '全名', // 表单字段的标题
      'field': 'fullName', // 字段名称
      'validator': 'isRequired', // 验证器
      'type': 'text', // 字段类型
    },
    {
      'title': '年龄', // 表单字段的标题
      'field': 'age', // 字段名称
      'type': 'number', // 字段类型
    },
    {
      'title': '性别', // 表单字段的标题
      'field': 'gender', // 字段名称
      'type': 'select', // 字段类型
      "options": ["男", "女", "不愿意透露"], // 下拉选项
    },
  ]
}).create();

更多关于Flutter自动表单生成插件autoform的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自动表单生成插件autoform的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


autoform 是一个用于 Flutter 的自动表单生成插件,它可以帮助开发者快速生成表单,并自动处理表单的验证和提交逻辑。使用 autoform 可以大大减少手动编写表单的工作量,并提高代码的可维护性。

安装

首先,你需要在 pubspec.yaml 文件中添加 autoform 依赖:

dependencies:
  flutter:
    sdk: flutter
  autoform: ^1.0.0  # 请根据最新版本号进行替换

然后运行 flutter pub get 来安装依赖。

基本用法

1. 导入包

import 'package:autoform/autoform.dart';

2. 定义表单字段

autoform 支持多种类型的表单字段,如 TextFieldDropdownButtonCheckbox 等。你可以通过 AutoFormField 来定义这些字段。

final formFields = [
  AutoFormField(
    name: 'name',
    type: AutoFormFieldType.text,
    label: 'Name',
    required: true,
  ),
  AutoFormField(
    name: 'email',
    type: AutoFormFieldType.email,
    label: 'Email',
    required: true,
  ),
  AutoFormField(
    name: 'password',
    type: AutoFormFieldType.password,
    label: 'Password',
    required: true,
  ),
  AutoFormField(
    name: 'gender',
    type: AutoFormFieldType.dropdown,
    label: 'Gender',
    options: ['Male', 'Female', 'Other'],
    required: true,
  ),
  AutoFormField(
    name: 'agree',
    type: AutoFormFieldType.checkbox,
    label: 'I agree to the terms and conditions',
    required: true,
  ),
];

3. 创建表单

使用 AutoForm 组件来创建表单,并将定义好的表单字段传递给它。

class MyForm extends StatelessWidget {
  final _formKey = GlobalKey<AutoFormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AutoForm Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: AutoForm(
          key: _formKey,
          fields: formFields,
          onSubmit: (Map<String, dynamic> values) {
            print('Form submitted with values: $values');
            // 在这里处理表单提交逻辑
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            _formKey.currentState!.submit();
          }
        },
        child: Icon(Icons.check),
      ),
    );
  }
}

4. 表单验证与提交

AutoForm 会自动处理表单的验证逻辑。你可以通过 _formKey.currentState!.validate() 来手动触发验证,并通过 _formKey.currentState!.submit() 来提交表单。

高级用法

自定义验证规则

你可以为每个字段添加自定义的验证规则:

AutoFormField(
  name: 'age',
  type: AutoFormFieldType.number,
  label: 'Age',
  required: true,
  validator: (value) {
    if (int.parse(value!) < 18) {
      return 'You must be at least 18 years old';
    }
    return null;
  },
),

自定义表单字段

如果你需要自定义表单字段,可以通过 AutoFormField.custom 来实现:

AutoFormField.custom(
  name: 'customField',
  label: 'Custom Field',
  builder: (context, field) {
    return TextFormField(
      decoration: InputDecoration(labelText: field.label),
      onChanged: (value) {
        field.didChange(value);
      },
    );
  },
),
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!