LoForm
LoForm 仍处于实验阶段,可能会出现缺失功能和错误。
LoForm 是一个低代码、轻量级的 Flutter 表单库,其灵感来自 Formik — 这是 React 最流行的表单库,已在 Airbnb、Stripe、NASA 等公司生产环境中使用。
特点
- 无样板代码: 与 bloc + formz 相比,代码量减少 90%。
- 信息丰富: 为表单中的每个字段提供许多有用的状态(
touched、status、error)。 - 对服务器错误友好: 与 flutter_form_builder 不同,它需要通过单独的状态来管理外部错误。
- 可重用且易于验证: 使用构建器模式来构建验证。
简单用法
这是一个简单的示例,更复杂的示例请参阅 RegisterForm 小部件。
class SimpleForm extends StatelessWidget {
@override
Widget build(BuildContext context) {
// [1] Wrap your form with [LoForm] widget.
return LoForm(
// [2] Choose when the submit button is enabled using form status.
submittableWhen: (status) => status.isValid || status.isSubmitted,
// [3] Implement what happens when the form is submitted.
onSubmit: (values) async {
print('Hi, ${values.get('name')}!');
return true; // Successful submission
},
builder: (form) {
return Column(
children: [
// [4] Use [LoTextField] instead of the normal [TextField].
LoTextField(
// [5] This name will be used to get the field's value.
name: 'name',
// [6] Provide a validation scheme using [LoValidation].
validate: LoValidation().required().build(),
),
const SizedBox(height: 32),
ElevatedButton(
// [7] Call the [submit] method.
onPressed: form.submit,
child: const Text('Submit'),
),
],
);
},
);
}
}