Flutter FormBuilder은 레이아웃 코드를 줄이고 재사용 가능한 검증 로직을 가능하게 하며 반응형 폼 처리를 제공함으로써 Flutter에서 폼 생성을 간소화합니다. 개발자는 폼 상태를 쉽게 관리하고 사용자 입력 변경에 대응하며 완료된 폼에서 구조화된 데이터를 수집할 수 있습니다. 이 패키지는 여러 플랫폼을 지원하며 Flutter 위젯 시스템과 원활하게 통합되어 동적이고 검증된 폼을 효율적으로 구축하는 데 이상적입니다.
사용 사례
실시간 검증을 사용하여 동적 폼 만들기
여러 폼 필드에서 검증 규칙 재사용하기
최소한의 코드로 복잡한 중첩 폼 만들기
구조화된 데이터 출력을 사용하여 폼 제출 처리
사용자 입력에 따라 반응형 폼 동작 구현
주요 기능
반복되는 폼 코드를 줄입니다
사용자 지정 및 내장 검증기 지원
반응형 폼 상태 관리 제공
간편한 폼 리셋 및 제출을 가능하게 합니다
Flutter의 네이티브 위젯과 통합됩니다
적합한 대상
데이터 수집 양식을 구축하는 개발자
유지보수 가능한 폼 코드를 우선시하는 팀
일관된 검증 로직이 필요한 프로젝트
다단계 또는 조건부 폼이 있는 앱
크로스 플랫폼 앱을 위한 Flutter를 사용하는 프론트엔드 개발자
고려 사항
Flutter의 상태 관리에 대한 이해가 필요합니다
복잡한 검증 시나리오를 위한 추가 설정이 필요할 수 있습니다
고급 사용 사례를 위한 제한된 문서
예측 가능한 구조를 가진 양식에 가장 적합
추가 작업 없이 고도로 맞춤형 폼 렌더링에 적합하지 않음
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
Flutter Form Builder
This package helps in creation of data collection forms in Flutter by removing the boilerplate needed to build a form, validate fields, react to changes and collect final user input.
Also included are common ready-made form input fields for FormBuilder. This gives you a convenient way of adding common ready-made input fields instead of creating your own FormBuilderField from scratch.
Call for Maintainers
We are looking for maintainers to contribute to the development and maintenance of Flutter Form Builder Ecosystem. Is very important to keep the project alive and growing, so we need your help to keep it up to date and with new features. You can contribute in many ways, we describe some of them in Support section.
FormBuilderCheckboxGroup - List of checkboxes for multiple selection
FormBuilderChoiceChip - Creates a chip that acts like a radio button.
FormBuilderDateRangePicker - For selection of a range of dates
FormBuilderDateTimePicker - For Date, Time and DateTime input
FormBuilderDropdown - Used to select one value from a list as a Dropdown
FormBuilderFilterChip - Creates a chip that acts like a checkbox
FormBuilderRadioGroup - Used to select one value from a list of Radio Widgets
FormBuilderRangeSlider - Used to select a range from a range of values
FormBuilderSlider - For selection of a numerical value on a slider
FormBuilderSwitch - On/Off switch field
FormBuilderTextField - A Material Design text field input
Parameters
In order to create an input field in the form, along with the label, and any applicable validation, there are several attributes that are supported by all types of inputs namely:
Attribute
Type
Default
Required
Description
name
String
Yes
This will form the key in the form value Map
initialValue
T
null
No
The initial value of the input field
enabled
bool
true
No
Determines whether the field widget will accept user input.
decoration
InputDecoration
InputDecoration()
No
Defines the border, labels, icons, and styles used to decorate the field.
validator
FormFieldValidator<T>
null
No
A FormFieldValidator that will check the validity of value in the FormField
onChanged
ValueChanged<T>
null
No
This event function will fire immediately the the field value changes
valueTransformer
ValueTransformer<T>
null
No
Function that transforms field value before saving to form value. e.g. transform TextField value for numeric field from String to num
The rest of the attributes will be determined by the type of Widget being used.
Use
Setup
No specific setup required: only install the dependency and use :)
Basic use
final _formKey = GlobalKey<FormBuilderState>();
FormBuilder(
key: _formKey,
child: FormBuilderTextField(
name: 'text',
onChanged: (val) {
print(val); // Print the text value write into TextField
},
),
)
final _formKey = GlobalKey<FormBuilderState>();
final _emailFieldKey = GlobalKey<FormBuilderFieldState>();
...
FormBuilder(
key: _formKey,
child: Column(
children: [
FormBuilderTextField(
key: _emailFieldKey,
name: 'email',
decoration: constInputDecoration(labelText: 'Email'),
validator: FormBuilderValidators.compose([
FormBuilderValidators.required(),
FormBuilderValidators.email(),
]),
),
ElevatedButton(
child: constText('Submit'),
onPressed: () async {
if(awaitcheckIfEmailExists()){
// Either invalidate using Form Key
_formKey.currentState?.fields['email']?.invalidate('Email already taken');
// OR invalidate using Field Key
_emailFieldKey.currentState?.invalidate('Email already taken');
}
},
),
],
),
),
Validation focus and auto-scroll options
validate and saveAndValidate can focus the first invalid field and scroll it
into view:
final isValid = _formKey.currentState?.saveAndValidate(
focusOnInvalid: true,
autoScrollWhenFocusOnInvalid: true,
);
focusOnInvalid defaults to true, and autoScrollWhenFocusOnInvalid defaults
to false. This is useful when the first invalid field is not a text field or
is inside a custom field that does not automatically scroll into view when
focused.
The same behavior can be used when setting a custom field error:
Starting with version 11.0.0 this package migrated to the official material_ui library. Properties exposing Material types (e.g. InputDecoration, DropdownMenuItem, ListTileControlAffinity) now use material_ui
types, so import package:material_ui/material_ui.dart instead of package:flutter/material.dart when configuring them. See the migration guide.
v9 to v10
Remove invalidateField and invalidateFirstField methods from FormBuilderState. Use fields[name]?.invalidate(errorText) and fields.first.invalidate(errorText) instead
[FormBuilderTextField] Deprecate canRequestFocus property. Use FocusNode.canRequestFocus. instead
Assert on FormBuilderField.decoration.enabled property. Use FormBuilderField.enabled instead
Easy way! Only need execute dart fix --apply on your project to fix the following changes:
Rename FormBuilderChoiceChip to FormBuilderChoiceChips.
Rename FormBuilderFilterChip to FormBuilderFilterChips.