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

패키지 상세v1.10.0

go_form

Flutter에서 입력 필드의 상태 및 검증을 관리하기 위한 일반적인 컨트롤러입니다. 초기 값, 검증, 오류 및 포커스를 지원합니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
409
좋아요
5
Pub 점수
150

패키지 설치

flutter pub add go_form

패키지 개요

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

go_form은 폼 입력 상태, 검증, 오류 및 포커스를 관리하기 위한 일반적인 컨트롤러를 제공하는 Flutter/Dart 패키지입니다. 초기 값, 실시간 검증, 오류 추적 및 포커스 관리를 통해 폼 필드 처리를 단순화합니다. 깔끔하고 재사용 가능한 폼 로직을 설계하여 빌더플레이트 코드를 줄이고 개발자 생산성을 향상시킵니다. Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼을 지원하며, 크로스플랫폼 애플리케이션에 이상적입니다. 가볍고 직관적인 API는 기존 폼에 쉽게 통합할 수 있도록 합니다.

사용 사례

  • 여러 입력 항목을 사용하여 동적 폼 관리
  • 실시간 검증 구현
  • 오류 피드백과 함께 폼 제출 처리
  • 재사용 가능한 폼 컴포넌트 만들기
  • 화면 간 폼 상태 관리를 단순화합니다
  • 필드 간 포커스 탐색 지원

주요 기능

  • 일반 입력 필드 컨트롤러
  • 실시간 검증 지원
  • 오류 메시지 관리
  • 입력 필드를 위한 포커스 제어
  • 초기 값 구성
  • 크로스 플랫폼 호환성

적합한 대상

  • Flutter에서 복잡한 폼을 구축하는 개발자
  • 재사용 가능한 폼 로직을 찾는 팀
  • 강력한 입력 검증이 필요한 앱
  • 다중 플랫폼을 대상으로 하는 프로젝트
  • 최소한의 블러러플레이트를 원하는 프론트엔드 개발자

고려 사항

  • Flutter의 상태 관리에 대한 이해가 필요합니다
  • 사용자 정의 UI를 위해 추가 스타일링이 필요할 수 있습니다
  • 매우 간단한 일회용 양식에는 적합하지 않습니다
  • 실행 시간 오류를 피하기 위해 올바른 초기화에 의존합니다
  • 더 넓은 상태 관리 없이 양식 전용 사용 사례에 국한됨

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

GoForm

Available Translations:


Pub

GoForm is a powerful library for managing forms in Flutter.
It allows you to dynamically create, validate, and manage form state
without the need to manually handle controllers for each field.

Features of GoForm

  • Smart validation with minimal code
    GoForm automatically validates input using standard validators,
    eliminating the need to manually write validation logic for each field.

  • Flexibility for any field types
    Create any form elements — from simple text fields and checkboxes
    to complex file pickers and dropdown menus.
    GoForm seamlessly adapts to any UI structure.

  • Centralized error management
    Set and reset errors anywhere in your code,
    without needing to use setState().
    Error display is fully automated and updates without unnecessary re-renders.

  • Debounced value changes
    Fields can debounce rapid input changes using debounceDuration, reducing unnecessary processing or validations.

  • Asynchronous validation
    Add asyncValidator to a field to perform validation that requires waiting for server responses or background checks.
    Use formController.validateAsync() to trigger validation across all fields.

  • Advanced focus management
    The FormController provides built-in methods for controlling focus between fields:

    • focus(String name) – focuses the field with the given name.
    • unfocus(String name) – removes focus from the specified field.
    • unfocusAll() – removes focus from all fields.
    • focusNext(String name) – moves focus to the next field.
    • focusPrevious(String name) – moves focus to the previous field.
    • focusFirstError() – focuses the first field that has a validation error.
    • hasFocus(String name) – returns true if the field is currently focused.
    • hasError(String name) – returns true if the field currently has an error.

Comparison of standard Flutter tools and GoForm
Feature GoForm Standard Flutter
Field management Fields are registered automatically Each field requires a TextEditingController
Field flexibility Supports any fields (text, files, checkboxes) Only TextFormField and standard widgets
Error handling Errors are set via FormController.setError() Errors can only be handled in validator
Centralized state management A single FormController manages the entire form Field states must be tracked manually
Retrieving values formController.getValues() returns a Map<String, dynamic> Requires accessing TextEditingController.text
Resetting fields formController.resetAllFields() Controllers must be cleared manually
Handling server-side errors Errors can be set using setError() Errors must be stored in setState()

How to Install

Add the dependency to pubspec.yaml:

dependencies:
  go_form: latest_version

Replace latest_version with the latest version from pub.dev.

Quick Start

Creating a Form with Dynamic Fields

In DynamicForm, simply pass a list of fields and a controller:


final _formController = FormController();

@override
Widget build(BuildContext context) {
  return DynamicForm(
    controller: _formController,
    fields: [
      GoTextInput(
        name: 'email',
        label: 'Email',
        validator: (val) => val == null || val.isEmpty ? 'Enter your email' : null,
      ),
      GoTextInput(
        name: 'password',
        label: 'Password',
        validator: (val) => val == null || val.length < 6 ? 'Minimum 6 characters' : null,
      ),
    ],
  );
}
Validation Check Before Submission
void onSubmit() {
  if (_formController.validate()) {
    print(_formController.getValues()); // Retrieving form data  
  } else {
    print(_formController.errors); // Displaying errors 
  }
}
Focus and Scrolling Example

GoForm allows you to programmatically manage focus and scroll behavior:

GoTextInput(
  name: 'email',
  label: 'Email',
),
GoTextInput(
  name: 'password',
  label: 'Password',
),

To move focus to the next field:

ElevatedButton(
  onPressed: () {
    _formController.focusNext('email');
  },
  child: Text('Go to Password'),
);

To focus the first field with a validation error:

ElevatedButton(
  onPressed: () async {
    final isValid = await _formController.validateAsync();
    if (!isValid) {
      _formController.focusFirstError();
    }
  },
  child: Text('Validate and Focus Error'),
);

To scroll to the first field with an error:

ElevatedButton(
  onPressed: () async {
    final isValid = await _formController.validateAsync();
    if (!isValid) {
      _formController.scrollToFirstErrorField();
    }
  },
  child: Text('Validate and Scroll to Error'),
);

scrollToFirstErrorField() works with DynamicForm and assumes the form is wrapped in a scrollable container (e.g. SingleChildScrollView).

Adding Errors
void onLogin() async {
  final response = await AuthAPI.login(
    email: _formController.getFieldValue<String>('email'),
    password: _formController.getFieldValue<String>('password'),
  );

  if (response.hasError) {
    _formController.setError('email', response.errors['email']);
    _formController.setError('password', response.errors['password']);
  }
}
Resetting the Form
_formController.resetAllFields
(); // Очистка значений  
_formController.resetAllErrors
(); // Очистка ошибок  

Validation Triggers

GoForm provides fine-grained control over when validation occurs through ValidationTrigger enum:

Trigger When it fires Best for
onSubmit Only when validate() is called Non-critical fields, confirmation fields
onValueChange Every time the field value changes Password strength, real-time feedback
onFocusLost When field loses focus (blur) Email format, most standard fields
onFocusGained When field gains focus Special cases, clearing errors
onDebounceComplete After debounce period ends Search fields, API calls
manual Only when explicitly called Custom validation logic
Recommended Patterns
1. User-Friendly Form (Recommended for most cases)
2. Strict Real-Time Validation
3. Conservative Approach
FormController(
  defaultValidationTriggers: {ValidationTrigger.onSubmit},
  // Validate only when user tries to submit
);
4. Mixed Strategy (Advanced)
final controller = FormController(
defaultValidationTriggers: {ValidationTrigger.onFocusLost},
validateOnlyAfterFirstSubmit: true,
);

// Email: standard behavior
controller.addTextField<String>(name: 'email', validator: emailValidator);

// Password: real-time validation for security
controller.addTextField<String>(
name: 'password',
validator: passwordValidator,
validationTriggers: {ValidationTrigger.onValueChange},
);

// Terms: only on submit (avoid annoyance)
controller.addTextField<bool>(
name: 'acceptTerms',
validator: termsValidator,
validationTriggers: {ValidationTrigger.onSubmit},
);

How to Create a Custom Field?

Simply extend FormFieldModelBase<T> and implement build():

class GoTextInput extends FormFieldModelBase<String> {
  final String label;

  GoTextInput({required super.name, super.validator, required this.label});

  @override
  Widget build(BuildContext context, FieldController controller) {
    return TextField(
      onChanged: controller.onChange,
      controller: controller.textController,
      decoration: InputDecoration(
        labelText: label,
        errorText: controller.error,
      ),
    );
  }
}
One-Time Initialization (onInit)

You can override the onInit method inside your custom field to perform one-time setup logic.
This is useful for asynchronous operations, such as fetching initial data or triggering a service.

class MyCustomField extends FormFieldModelBase<String> {
  @override
  void onInit(FieldController<String> controller) {
    controller.setValue('initial_value');
  }

  @override
  Widget build(BuildContext context, FieldController<String> controller) {
    // widget build logic here
  }
}

About the author

My telegram channel - @kotelnikoff_dev

Contributions

Contributions are welcome! Feel free to open issues or create pull requests on the GitHub repository.

카테고리

소스 저장소

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

아직 데이터가 없습니다.