搜索插件、代码仓与 APP 分类

插件详情v5.2.7

fform

FForm 是一个 Dart 包,用于构建包含大量字段和验证的表单。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
137
喜欢数
184
Pub 分数
160

安装插件

flutter pub add fform

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

FForm 是一个 Dart 包,旨在简化具有大量字段和验证规则的复杂表单的创建。它提供了一种结构化、可重用的表单处理方法,减少了样板代码并提高了可维护性。FForm 专为 Flutter 设计,支持 Android、iOS、Web、macOS、Windows 和 Linux 等主要平台。该包使开发者能够高效地管理表单状态、验证输入并响应用户交互。凭借简洁的语法和直观的 API,FForm 简化了 Flutter 应用中的表单开发。

适合场景

  • 使用许多输入字段构建动态表单
  • 实现复杂的验证逻辑
  • 在多个屏幕之间管理表单状态
  • 创建可重用的表单组件
  • 处理表单提交并反馈错误

主要特点

  • 内置验证支持
  • 表单字段的状态管理
  • 可重用的表单控件
  • 跨平台兼容性
  • 最少的样板代码
  • 与 Flutter 的轻松集成

适合对象

  • 开发大型 Flutter 应用的开发者
  • 需要稳定表现模式的团队
  • 需要大量表单验证的项目
  • 具有多步骤或嵌套表单的应用程序
  • 专注于用户体验和表单可靠性的前端开发人员

使用建议

  • 对初学者来说可能需要一定的学习曲线
  • 与流行的替代方案相比,文档有限
  • 最适合表单使用频繁的项目
  • 不适合简单的单次表单
  • 依赖外部依赖项以实现高级功能

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

Logo Frame

Getting Started with FForm 🌟

Step 1: Installation

First things first, let's get the FForm package into your Flutter project. Add FForm to your pubspec.yaml file under dependencies:

dependencies:
  fform: ^latest_version

Don't forget to run flutter pub get in your terminal to install the package.

Overview

FForm is a high-level Flutter package designed to make form creation and management a breeze, with simplified field validation. It offers two main components: FFormField and FFormBuilder, that together bring ease and flexibility to your form handling in Flutter apps.

🧱 Core (Logic and Form Model)

  • FForm — the base class for forms, managing fields, validation, and state.
  • FFormField<T, E> — a generic form field supporting values, errors, and reactions to changes.
  • FFormException — the base class for exceptions that define validation errors.
  • FFormObserver — a static observer that monitors events across all forms (e.g., for debugging, logging, side-effects).

🧩 Widget (UI Binding Widgets)

  • FFormBuilder — binds the form to the UI, updating the interface on changes.
  • FFormProvider — provides access to the form through BuildContext.

🎯 Mixin (Additional Behavior for Fields)

  • KeyedField — adds a unique key for identifying the field in the tree.
  • AsyncField — supports asynchronous validation of the field.
  • CachedField — stores the previous value for reuse.
  • FocusedField — tracks focus, allowing reactions to focus gain/loss.

Structure

Why It Rocks 🎸

  • State Management Simplified: Automatically handles the state of both individual form fields and the form as a whole.
  • Built-in Validation with a Twist: Supports on-the-fly validation and error handling for each field, ensuring a smooth user experience.
  • Flexibility at Its Finest: Supports any data type for field values and validation errors thanks to generics.
  • Reactive Forms for the Win: Leverages streams for tracking form state changes, ensuring your UI is always in sync.
  • Multiple Forms, No Problem: Create multiple forms with custom fields and validation rules, all managed seamlessly by FForm.
  • Custom Exceptions for Custom Needs: Define custom exceptions for form fields to handle complex validation rules and error messages with ease.
  • AsyncValidator: Supports asynchronous validation for form fields, allowing you to validate data against external sources or APIs.
  • CachedField: Provides cached value for field, used to manage the state of the widget and access it in the widget tree.
  • FFormObserver: Allows you to observe the form state and trigger side effects based on the form's state changes.

Previews

Usage Examples

FFormField

FFormField is a base class for all form fields, supporting values, on-the-fly validation, and change handling. It provides a set of getters and methods to manage the field state, including checking the field's validity, retrieving the current value, and handling exceptions.

Example
enum EmailError {
  empty,
  not;

  @override
  String toString() {
    switch (this) {
      case empty:
        return 'emailEmpty';
      case not:
        return 'invalidFormatEmail';
      default:
        return 'invalidFormatEmail';
    }
  }
}

class EmailField extends FFormField<String, EmailError> {

  EmailField({required String value}) : super(value);

  @override
  EmailError? validator(value) {
    if (value.isEmpty) return EmailError.empty;
    return null;
  }
}
FForm

FForm is a base class for creating custom form classes with specific fields and validation rules. It provides a set of getters and methods to manage the form state, including checking the form's validity, retrieving answers, and handling exceptions.

Example

This is a simple example of how to create a form with a single field. You can extend the FForm class to create custom forms with specific fields and validation rules.

class LoginForm extends FForm {
  EmailField email;
  
  LoginForm({
    required this.email,
  }): super(fields: [email]);
}

This is a more complex example of how to create a form with multiple fields. You can extend the FForm class to create custom forms with specific fields and validation rules.

class Form extends FForm {
  List<Form> forms;

  Form({
    required this.forms,
  }): super(subForms: forms);
}
FFormBuilder

FFormBuilder is a widget that constructs and manages the form state, utilizing streams to refresh the UI dynamically as data changes. It provides a builder function that takes the form and returns a widget tree based on the form's state.

Example

This is an example of how to use FFormBuilder to create a form with a single field. The builder function takes the form as a parameter and returns a widget tree based on the form's state.

void _submit() {
  if(_form.check()) { // .isValid or .isInvalid start rebuild in FFormBuilder and returned boolean
    print('Form Valid');
  };
}

@override
Widget build(BuildContext context) {
  return FFormBuilder<LoginForm>(
    form: _form,
    builder: (context, form, child) {
      EmailField email = form.email; // or FFormProvider.of<LoginForm>(context).get<NameField>()
      
      return Column(
        children: [
          TextField(
            key: email.key,
            controller: _emailController,
            decoration: InputDecoration(
              labelText: 'Email',
              errorText: email.exception.toString(),
            ),
          ),
          ElevatedButton(
            onPressed: _submit,
            child: const Text('Submit'),
          ),
        ],
      );
    },
  );
}

You can use ListenableBuilder to rebuild only the field that has changed, but you can use FFormProvider to rebuild all fields in the form.

void _submit() {
  if(_form.check()) { // .isValid or .isInvalid start rebuild in FFormBuilder and returned boolean
    print('Form Valid');
  };
}

@override
Widget build(BuildContext context) {
  return ListenableBuilder<LoginForm>(
    listenable: _form,
    builder: (context, form, child) {
      EmailField email = form.email; // or FFormProvider.of<LoginForm>(context).get<NameField>()
      
      return Column(
        children: [
          TextField(
            key: email.key,
            controller: _emailController,
            decoration: InputDecoration(
              labelText: 'Email',
              errorText: email.exception.toString(),
            ),
          ),
          ElevatedButton(
            onPressed: _submit,
            child: const Text('Submit'),
          ),
        ],
      );
    },
  );
}

FFormProvider

FFormProvider is a widget that allows you to access the form in the widget tree without passing it as a parameter.

Example
FFormBuilder<LoginForm>(
  form: _form,
  builder: (context, form) {
    
    FFormProvider.of<LoginForm>(context).email; // or form.email;
    FFormProvider.of<LoginForm>(context).get<NameField>(); // or form.get<NameField>();

    return YourForm();
  },
)
FFormException

FFormException is a base class for creating custom exceptions for form fields. It allows you to define custom validation rules and error messages for form fields, enabling you to handle complex validation scenarios with ease.

Example

You can create a custom exception class that extends FFormException to define specific validation rules and error messages for a form field.

class PasswordValidationException extends FFormException {
  final bool isMinLengthValid;
  final bool isSpecialCharValid;
  final bool isNumberValid;

  PasswordValidationException({
    required this.isMinLengthValid,
    required this.isSpecialCharValid,
    required this.isNumberValid,
  });

  @override
  bool get isValid => isMinLengthValid && isSpecialCharValid && isNumberValid;
}

class PasswordField extends FFormField<String, PasswordValidationException> {
  PasswordField(String value) : super(value);

  @override
  PasswordValidationException? validator(String value) {
    final validator = FFormValidator(value);
    return PasswordValidationException(
      isMinLengthValid: validator.isMinLength(8),
      isSpecialCharValid: validator.isHaveSpecialChar,
      isNumberValid: validator.isHaveNumber,
    );
  }
}
FFormObserver

FFormObserver is a widget that allows you to observe the form state and trigger side effects based on the form's state changes. It provides a builder function that takes the form as a parameter and returns a widget tree based on the form's state.

Example
class MyFFormObserver extends FFormObserver {
  @override
  void check(FForm form) {
    if (kDebugMode) {
      print('Form has been checked and is ${form.isValid ? 'valid' : 'invalid'}');
    }
  }
}
FFormField mixins
And you can add KeyedField mixin to get a unique key for identifying the form field widget.
class EmailField extends FFormField<String, EmailError> with KeyedField {

  EmailField({required String value}) : super(value);

  @override
  EmailError? validator(value) {
    if (value.isEmpty) return EmailError.empty;
    return null;
  }
}

// and get GlobalKey -> form.email.key 
And you can use AsyncValidator
class EmailField extends FFormField<String, EmailError> with AsyncField<String, EmailError> {

  EmailField({required String value}) : super(value);

  @override
  EmailError? validator(value) {
    if (value.isEmpty) return EmailError.empty;
    return null;
  }

  @override
  Future<EmailError?> asyncValidator(value) async {
    await Future.delayed(Duration(seconds: 1));
    if (!value.contains('@')) return EmailError.not;
    return null;
  }
}

// final field = EmailField();
// if(await field.check()) {
//     
// }
Cached value for field
class EmailField extends FFormField<String, EmailError> with CachedField<String, EmailError> {

  EmailField({required String value}) : super(value);

  @override
  EmailError? validator(value) {
    if (value.isEmpty) return EmailError.empty;
    return null;
  }

}
Focused Field
class EmailField extends FFormField<String, EmailError> with FocusField<String, EmailError> {

  EmailField({required String value}) : super(value);

  @override
  EmailError? validator(value) {
    if (value.isEmpty) return EmailError.empty;
    return null;
  }

}

// final field = EmailField();
// if(field.check()) {
//   ....
// } else {
//    field.focus.requestFocus();
// }
FFormStatus

FFormStatus is an enum that represents the various states of a form (FForm) during its lifecycle. It helps track the form's status, such as whether it's idle, processing, successfully validated, or has encountered errors.

Enum Values
  • initial: The default state of the form before any action is taken.
  • loading: Indicates that the form is currently processing, such as during validation or submission.
  • success: Indicates that the form has successfully completed its operation with no validation errors.
  • exception: Indicates that the form has encountered errors, such as validation failures.
Example
switch(_form.status) {
   FFormStatus.initial => print('initial'),
   FFormStatus.loading => print('loading'),
   FFormStatus.success => print('success'),
   FFormStatus.exception => print('exception'),
};

Examples

Codecov

Codecov

所属分类

依赖

依赖清单 2 项

源码仓库

使用此插件的项目

暂无相关数据。