Flutter动态表单构建插件dynamic_form_builder的使用

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

Flutter动态表单构建插件dynamic_form_builder的使用

Dynamic Form Builder 是一个用于 Flutter 的包,它允许你创建具有多种类型表单字段的动态表单。它提供了一种灵活且易于使用的基于表单字段定义列表来构建表单的方法。

功能

  • 使用多种类型的字段创建动态表单。
  • 支持自定义验证器。
  • 可以轻松集成 FormBuilderflutter_form_builder 包。

安装

在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  dynamic_form_builder: 0.0.1

示例代码

以下是使用 Dynamic Form Builder 创建一个动态表单的示例代码:

import 'package:dynamic_form_builder/dynamic_form_builder.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '动态表单示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyFormPage(),
    );
  }
}

class MyFormPage extends StatelessWidget {
  final GlobalKey<FormBuilderState> _formKey = GlobalKey<FormBuilderState>();

  MyFormPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('动态表单')),
      body: Padding(
        padding: const EdgeInsets.all(18.0),
        child: DynamicForm(
          formKey: _formKey,
          fieldValues: const {},
          fieldsToUse: [
            TextFieldBase(
              name: 'Name',
              isRequired: true,
              validators: [
                MaxLengthValidator(params: 10, errorMessage: '最多10个字符') // 最多10个字符
              ],
            ),
            DropdownFieldBase(
              name: 'Gender',
              options: ['男', '女'], // 性别选项
            ),
            CheckboxFieldBase(
              name: 'Interests',
              options: ['体育', '音乐', '旅行'], // 兴趣选项
            ),
            RadioFieldBase(
              name: 'Marital Status',
              options: ['单身', '已婚'], // 婚姻状态选项
            ),
            DateFieldBase(
              name: 'Date of Birth',
              initialValue: DateTime(2000, 1, 1), // 初始日期
            ),
            FileFieldBase(
              name: 'Profile Picture',
              allowMultiple: false, // 不允许多选
              pickImagesOnly: true, // 仅选择图片
            ),
          ],
          onChanged: (key, value) {
            // 处理字段变化
          },
          onSubmit: () {
            // 处理表单提交
          },
        ),
      ),
    );
  }
}

代码说明

  1. 导入包

    import 'package:dynamic_form_builder/dynamic_form_builder.dart';
    import 'package:flutter/material.dart';
    
  2. 主应用类

    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: '动态表单示例',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyFormPage(),
        );
      }
    }
    
  3. 表单页面类

    class MyFormPage extends StatelessWidget {
      final GlobalKey<FormBuilderState> _formKey = GlobalKey<FormBuilderState>();
    
      MyFormPage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text('动态表单')),
          body: Padding(
            padding: const EdgeInsets.all(18.0),
            child: DynamicForm(
              formKey: _formKey,
              fieldValues: const {},
              fieldsToUse: [
                TextFieldBase(
                  name: 'Name',
                  isRequired: true,
                  validators: [
                    MaxLengthValidator(params: 10, errorMessage: '最多10个字符')
                  ],
                ),
                DropdownFieldBase(
                  name: 'Gender',
                  options: ['男', '女'],
                ),
                CheckboxFieldBase(
                  name: 'Interests',
                  options: ['体育', '音乐', '旅行'],
                ),
                RadioFieldBase(
                  name: 'Marital Status',
                  options: ['单身', '已婚'],
                ),
                DateFieldBase(
                  name: 'Date of Birth',
                  initialValue: DateTime(2000, 1, 1),
                ),
                FileFieldBase(
                  name: 'Profile Picture',
                  allowMultiple: false,
                  pickImagesOnly: true,
                ),
              ],
              onChanged: (key, value) {
                // 处理字段变化
              },
              onSubmit: () {
                // 处理表单提交
              },
            ),
          ),
        );
      }
    }
    

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

1 回复

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


当然,下面是一个关于如何使用 dynamic_form_builder 插件在 Flutter 中构建动态表单的代码示例。dynamic_form_builder 是一个强大的插件,允许你根据 JSON 数据动态生成表单。

首先,确保你的 pubspec.yaml 文件中已经添加了 dynamic_form_builder 依赖:

dependencies:
  flutter:
    sdk: flutter
  dynamic_form_builder: ^latest_version  # 请替换为最新版本号

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

接下来,编写一个示例应用,展示如何使用 dynamic_form_builder

import 'package:flutter/material.dart';
import 'package:dynamic_form_builder/dynamic_form_builder.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dynamic Form Builder Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: DynamicFormScreen(),
    );
  }
}

class DynamicFormScreen extends StatefulWidget {
  @override
  _DynamicFormScreenState createState() => _DynamicFormScreenState();
}

class _DynamicFormScreenState extends State<DynamicFormScreen> {
  // 示例表单 JSON 数据
  final String formJson = '''
  [
    {
      "type": "text",
      "label": "First Name",
      "name": "first_name",
      "required": true
    },
    {
      "type": "text",
      "label": "Last Name",
      "name": "last_name",
      "required": true
    },
    {
      "type": "email",
      "label": "Email",
      "name": "email",
      "required": true
    },
    {
      "type": "dropdown",
      "label": "Gender",
      "name": "gender",
      "options": [
        {"value": "male", "display": "Male"},
        {"value": "female", "display": "Female"}
      ],
      "required": true
    },
    {
      "type": "checkbox_list",
      "label": "Hobbies",
      "name": "hobbies",
      "options": [
        {"value": "reading", "display": "Reading"},
        {"value": "traveling", "display": "Traveling"},
        {"value": "swimming", "display": "Swimming"}
      ]
    },
    {
      "type": "submit",
      "label": "Submit"
    }
  ]
  ''';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dynamic Form Builder Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: FutureBuilder<List<FormBuilderField>>(
          future: parseJsonToFormFields(formJson),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}'));
            } else {
              final formFields = snapshot.data!;
              return FormBuilder(
                fields: formFields,
                onSubmit: (values) {
                  // 处理表单提交
                  print(values);
                },
              );
            }
          },
        ),
      ),
    );
  }
}

// 解析 JSON 到 FormBuilderField 列表的辅助函数
Future<List<FormBuilderField>> parseJsonToFormFields(String jsonString) async {
  final jsonData = await jsonDecode(jsonString);
  final List<FormBuilderField> formFields = [];

  if (jsonData is List<dynamic>) {
    for (final item in jsonData) {
      FormBuilderField field;

      switch (item['type']) {
        case 'text':
          field = FormBuilderTextField(
            label: item['label'],
            name: item['name'],
            required: item['required'] ?? false,
          );
          break;
        case 'email':
          field = FormBuilderEmailField(
            label: item['label'],
            name: item['name'],
            required: item['required'] ?? false,
          );
          break;
        case 'dropdown':
          final options = item['options']
              ?.map<DropdownMenuItem<String>>(
                  (option) => DropdownMenuItem(value: option['value'], child: Text(option['display'])))
              .toList();
          field = FormBuilderDropdownField(
            label: item['label'],
            name: item['name'],
            required: item['required'] ?? false,
            options: options,
          );
          break;
        case 'checkbox_list':
          final options = item['options']
              ?.map<CheckboxListTile<String>>(
                  (option) => CheckboxListTile(
                        title: Text(option['display']),
                        value: option['value'],
                      ))
              .toList();
          field = FormBuilderCheckboxListField(
            label: item['label'],
            name: item['name'],
            required: item['required'] ?? false,
            options: options,
          );
          break;
        case 'submit':
          field = FormBuilderSubmitField(
            label: item['label'],
          );
          break;
        default:
          throw UnsupportedError('Unsupported field type: ${item['type']}');
      }

      formFields.add(field);
    }
  } else {
    throw FormatException('Invalid JSON format');
  }

  return formFields;
}

在这个示例中,我们定义了一个 JSON 字符串,其中包含表单的各种字段类型(如文本、电子邮件、下拉菜单和复选框列表)。然后,我们使用 FutureBuilder 来异步解析 JSON 数据并生成相应的 FormBuilderField 列表。最后,我们将这些字段传递给 FormBuilder 组件,以渲染动态表单。

你可以根据需要扩展和修改这个示例,以适应你的具体需求。

回到顶部