Flutter快速表单构建插件flutter_fast_forms的使用
Flutter快速表单构建插件flutter_fast_forms的使用
Flutter Fast Forms 是一个用于快速构建 Flutter 表单的 Dart 包。它为 Flutter SDK 添加了一些缺失的功能,简化了表单的创建和管理。以下是关于如何使用 flutter_fast_forms
的详细介绍。
目录
概述
功能特性
- FastFormControl<T>:封装了 Material 和 Cupertino 表单控件,方便快捷地创建表单字段。
- FastForm:提供当前表单字段值的
onChanged
回调。 - FastFormArray:聚合多个同类型控件。
- FastChipsInput:将文本输入转换为芯片(Chip)。
- 条件表单字段:根据其他字段的状态动态启用或禁用字段。
- 验证状态:支持
touched
状态的验证。 - 常用验证器:提供常用的
FormFieldValidator<T>
函数。
开始使用
1. 添加 FastForm
到你的 widget 树中
class MyFormPage extends StatelessWidget {
MyFormPage({Key? key, required this.title}) : super(key: key);
final formKey = GlobalKey<FormState>();
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: SafeArea(
child: SingleChildScrollView(
child: FastForm(
formKey: formKey,
children: [],
),
),
),
);
}
}
2. 添加 FastFormControl<T>
子控件到 FastForm
FastForm(
formKey: formKey,
children: [
const FastTextField(
name: 'field_destination',
labelText: 'Destination',
placeholder: 'Where are you going?',
),
FastDateRangePicker(
name: 'field_check_in_out',
labelText: 'Check-in - Check-out',
firstDate: DateTime.now(),
lastDate: DateTime.now().add(const Duration(days: 365)),
),
const FastCheckbox(
name: 'field_travel_purpose',
labelText: 'Travel purpose',
titleText: 'I am travelling for work',
),
],
),
3. 使用 FastFormSection
进行视觉分组和一致的内边距
FastForm(
formKey: formKey,
children: [
FastFormSection(
header: const Text('My Form'),
padding: EdgeInsets.all(16.0),
children: [
const FastTextField(
name: 'field_destination',
labelText: 'Destination',
placeholder: 'Where are you going?',
),
// ...
],
),
]
),
控件目录
FastFormControl<T> | 字段值类型 | 封装的 Material 组件 | 封装的 Cupertino 组件 (adaptive: true) |
---|---|---|---|
FastAutocomplete<O> | String | Autocomplete<O> | no |
FastCheckbox | bool | CheckboxListTile | CupertinoCheckbox |
FastChoiceChips<T> | Set<T> | ChoiceChip | no |
FastCalendar | DateTime | CalendarDatePicker | no |
FastChipsInput | List<String> | RawAutocomplete<String> + InputChip | no |
FastDatePicker | DateTime | showDatePicker | CupertinoDatePicker |
FastDateRangePicker | DateTimeRange | showDateRangePicker | no |
FastDropdown<T> | T | DropdownButtonFormField<T> | no |
FastRadioGroup<T> | T | RadioListTile<T> | no |
FastRangeSlider | RangeValues | RangeSlider | no |
FastSegmentedButton<T> | Set<T> | SegmentedButton<T> | no |
FastSegmentedControl<T> | T extends Object | no | CupertinoSlidingSegmentedControl<T> |
FastSlider | double | Slider.adaptive | CupertinoSlider |
FastSwitch | bool | SwitchListTile | CupertinoSwitch |
FastTextField | String | TextFormField | CupertinoTextFormFieldRow |
FastTimePicker | TimeOfDay | showTimePicker | no (使用 FastDatePicker with CupertinoDatePickerMode.time) |
自适应表单控件
默认情况下,Flutter Fast Forms 在所有平台上使用 Material 风格的组件。可以通过设置 adaptive
属性为 true
来在 iOS 上自动渲染对应的 Cupertino 组件。
示例:在 iOS 上始终使用 Cupertino 组件
FastForm(
formKey: formKey,
adaptive: true,
children: [
const FastSwitch(
name: 'switch',
titleText: 'Disable text field',
),
FastTextField(
name: 'text_field',
labelText: 'Just some sample text field',
),
]
),
示例:仅在 iOS 上使用 Cupertino 组件
FastForm(
formKey: formKey,
children: [
const FastSwitch(
name: 'switch',
adaptive: true,
titleText: 'Disable text field when selected',
),
]
),
条件表单控件
通过条件表单控件,可以根据其他控件的状态动态启用或禁用某些字段。
示例:当开关被选中时禁用文本框
const FastSwitch(
name: 'switch',
titleText: 'Disable text field when selected',
),
FastTextField(
name: 'text_field',
labelText: 'Just some sample text field',
conditions: {
FastCondition.disabled: FastConditionList([
FastCondition(
target: 'switch',
test: (value, field) => value is bool && value,
),
]),
},
),
示例:当开关或复选框被选中时启用文本框
const FastCheckbox(
name: 'checkbox',
titleText: 'Enable text field when selected',
),
const FastSwitch(
name: 'switch',
titleText: 'Enable text field when selected',
),
FastTextField(
name: 'text_field',
enabled: false,
labelText: 'Just some sample text field',
conditions: {
FastCondition.enabled: FastConditionList([
FastCondition(
target: 'switch',
test: (value, field) => value is bool && value,
),
FastCondition(
target: 'checkbox',
test: (value, field) => value is bool && value,
),
]),
},
),
示例:当开关和复选框都被选中时禁用文本框
const FastCheckbox(
name: 'checkbox',
titleText: 'Disable text field when selected',
),
const FastSwitch(
name: 'switch',
titleText: 'Disable text field when selected',
),
FastTextField(
name: 'text_field',
labelText: 'Just some sample text field',
conditions: {
FastCondition.enabled: FastConditionList(
[
FastCondition(
target: 'switch',
test: (value, field) => value is bool && value,
),
FastCondition(
target: 'checkbox',
test: (value, field) => value is bool && value,
),
],
match: FastConditionMatch.every,
),
},
),
自定义表单控件
有时你需要添加非标准的控件到表单中。通过继承 FastFormField<T>
并实现 FormFieldBuilder<T>
,你可以创建自定义的表单控件。
示例:创建一个生成随机整数的自定义控件
1. 创建继承自 FastFormField<int>
的类
class MyCustomField extends FastFormField<int> {
const MyCustomField({
super.builder = myCustomFormFieldBuilder,
super.key,
required super.name,
});
@override
MyCustomFieldState createState() => MyCustomFieldState();
}
class MyCustomFieldState extends FastFormFieldState<int> {
@override
MyCustomField get widget => super.widget as MyCustomField;
}
2. 实现 FormFieldBuilder<int>
返回自定义控件
Widget myCustomFormFieldBuilder(FormFieldState<int> field) {
final state = field as MyCustomFieldState;
final decoration = state.decoration;
final didChange = state.didChange;
final value = state.value;
return InputDecorator(
decoration: decoration,
child: Row(
children: [
ElevatedButton(
child: const Text('Create random number'),
onPressed: () => didChange(Random().nextInt(1 << 32)),
),
if (value is int)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: Text(value.toString()),
)
],
),
);
}
3. 添加所有支持的超初始化参数
class MyCustomField extends FastFormField<int> {
const MyCustomField({
super.builder = myCustomFormFieldBuilder,
super.decoration,
super.enabled,
super.helperText,
super.initialValue,
super.key,
super.labelText,
required super.name,
super.onChanged,
super.onReset,
super.onSaved,
super.onTouched,
super.validator,
});
@override
MyCustomFieldState createState() => MyCustomFieldState();
}
通过以上步骤,你可以轻松创建并使用自定义表单控件。
希望这些内容能帮助你更好地理解和使用 flutter_fast_forms
插件。如果你有任何问题或需要进一步的帮助,请随时提问!
更多关于Flutter快速表单构建插件flutter_fast_forms的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter快速表单构建插件flutter_fast_forms的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用flutter_fast_forms
插件来快速构建表单的一个示例。flutter_fast_forms
插件允许你通过JSON配置快速生成表单,极大地减少了手动编写UI代码的工作量。
首先,确保你已经在pubspec.yaml
文件中添加了flutter_fast_forms
依赖:
dependencies:
flutter:
sdk: flutter
flutter_fast_forms: ^最新版本号 # 请替换为实际可用的最新版本号
然后,运行flutter pub get
来安装依赖。
接下来是一个完整的示例,展示如何使用flutter_fast_forms
来构建一个表单:
import 'package:flutter/material.dart';
import 'package:flutter_fast_forms/flutter_fast_forms.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Fast Forms Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// 表单数据
final formKey = GlobalKey<FormState>();
Map<String, dynamic> formData = {};
// 表单配置(JSON格式)
final formConfig = [
{
"type": "text",
"label": "Name",
"name": "name",
"required": true,
"validator": "This field is required"
},
{
"type": "email",
"label": "Email",
"name": "email",
"required": true,
"validator": "Please enter a valid email address"
},
{
"type": "number",
"label": "Age",
"name": "age",
"required": true,
"validator": "Please enter a valid age"
},
{
"type": "checkbox",
"label": "Accept Terms",
"name": "acceptTerms",
"required": true,
"validator": "You must accept the terms"
},
{
"type": "button",
"typeValue": "submit",
"label": "Submit",
"onPressed": () {
if (formKey.currentState!.validate()) {
formKey.currentState!.save();
print("Form Data: $formData");
// 在这里处理表单提交逻辑
}
}
}
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Fast Forms Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: formKey,
child: FastForm(
formConfig: formConfig,
formData: formData,
onFieldChange: (name, value) {
setState(() {
formData[name] = value;
});
},
),
),
),
);
}
}
在这个示例中,我们做了以下几件事:
-
定义表单配置:
formConfig
是一个JSON数组,定义了表单的各个字段,包括字段类型、标签、名称、是否必填以及验证信息。 -
创建表单状态:使用
Form
和GlobalKey<FormState>
来管理表单的状态。 -
使用
FastForm
组件:将formConfig
和formData
传递给FastForm
组件,并处理字段变化事件。 -
处理表单提交:在“Submit”按钮的
onPressed
回调中,验证表单并保存数据。
这个示例展示了如何使用flutter_fast_forms
插件快速构建并管理表单。你可以根据需要扩展formConfig
数组来添加更多字段和配置。