패키지, 저장소 및 앱 카테고리 검색

패키지 상세v5.2.7

fform

FForm은 많은 필드와 검증을 가진 폼을 만들기 위한 다트 패키지입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
137
좋아요
184
Pub 점수
160

패키지 설치

flutter pub add fform

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

FForm은 수많은 필드와 검증 규칙을 가진 복잡한 폼을 쉽게 만들 수 있도록 설계된 Dart 패키지입니다. 구조적이고 재사용 가능한 폼 처리 방식을 제공하여 반복 코드를 줄이고 유지보수성을 높입니다. Flutter 전용으로 개발되었으며 Android, iOS, Web, macOS, Windows, Linux 등 주요 플랫폼을 모두 지원합니다. 이 패키지는 폼 상태 관리, 입력 검증, 사용자 상호작용에 대한 응답을 효율적으로 수행할 수 있게 해줍니다. 깔끔한 문법과 직관적인 API를 통해 FForm은 Flutter 애플리케이션에서 폼 개발을 간편하게 만듭니다.

사용 사례

  • 많은 입력 필드를 사용하여 동적 폼 만들기
  • 복잡한 검증 로직 구현
  • 여러 화면 간에 폼 상태 관리하기
  • 재사용 가능한 폼 컴포넌트 만들기
  • 오류 피드백과 함께 폼 제출 처리

주요 기능

  • 내장 검증 지원
  • 폼 필드에 대한 상태 관리
  • 재사용 가능한 폼 위젯
  • 크로스 플랫폼 호환성
  • 최소한의 보일러플레이트 코드
  • Flutter와의 간편한 통합

적합한 대상

  • 대규모 플러터 앱을 개발하는 개발자
  • 일관된 형태 패턴이 필요한 팀
  • 광범위한 양식 검증이 필요한 프로젝트
  • 다중 단계 또는 중첩 폼을 가진 애플리케이션
  • UX와 폼 신뢰성에 중점을 둔 프론트엔드 개발자

고려 사항

  • 초보자에게는 학습 곡선이 필요할 수 있습니다
  • 인기 있는 대안들에 비해 문서가 제한적
  • 많은 양의 폼을 사용하는 프로젝트에 적합
  • 간단한 단일 폼에는 적합하지 않음
  • 고급 기능을 위해 외부 종속성에 의존합니다

원본 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 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.