flutter_reactive_form 0.0.3 flutter_reactive_form: ^0.0.3 copied to clipboard
A reactive form for handling Form inputs and validation.
Minimum Requirements #
- Dart SDK: >=2.18.6 <4.0.0
- Flutter: >=1.17.0
Installation and Usage #
Once you're familiar with Flutter you may install this package adding flutter_reactive_form
to the dependencies list
of the pubspec.yaml
file as follow:
dependencies:
flutter:
sdk: flutter
flutter_reactive_form: ^0.0.1
Then run the command flutter packages get
on the console.
Creating a form #
A form is composed by multiple field controls.
To declare a form with the fields name and birthday is as simple as:
- name have a default value.
- birthday is null by default.
final form = ReactiveForm(
onChanged: (formData, fieldChanged) {
/// Handle the change.
},
formGroup:{
"name": FormFieldData<String>(
fieldEnum: "name",
name: "Name",
isRequired: true,
isEnabled: true,
data: "Nghi",
),
"birthday": FormFieldData<DateTime?>(
fieldEnum: "birthday",
name: "Birthday",
isRequired: true,
isEnabled: true,
data: null,
),
},
);
How to get/set Form's data #
You can get the value of a field:
String get name => _reactiveForm.getFieldData<String>(fieldEnum: 'name');
DateTime? get birthday => _reactiveForm.getFieldData<DateTime>(fieldEnum: 'birthday');
To set value to fields:
_reactiveForm.setFieldData(fieldEnum: 'name', data: "Kate");
Validations #
Set up your validations as follows:
_reactiveForm.setFormatValidationMap({
'birthday': (birthday) {
if (birthday == null || birthday.isAfter(DateTime.now())) {
return "The time is invalid";
}
return '';
},
});
To validate a field:
final fieldControl = _reactiveForm.getField(fieldEnum: 'name');
final error = _reactiveForm.validateFormatField(fieldControl!);
To validate a form:
final errors = _reactiveForm.validateFormatFields();
Using mixin #
There're available functions in ReactiveFormMixin that interface with the form internally:
class ProfileFormController with ReactiveFormMixin {
/// You can call it in state.initState()
void init() {
final form = ReactiveForm(
onChanged: (formData, fieldChanged) {
/// Handle the change.
},
formGroup: {
"name": FormFieldData<String>(
fieldEnum: "name",
name: "Name",
isRequired: true,
isEnabled: true,
data: "Nghi",
),
"birthday": FormFieldData<DateTime?>(
fieldEnum: "birthday",
name: "Birthday",
isRequired: true,
isEnabled: true,
data: null,
),
},
);
initForm(form);
setFormatValidationMap({
'birthday': (birthday) {
if (birthday == null || birthday.isAfter(DateTime.now())) {
return "The time is invalid";
}
return '';
},
});
}
/// Interact with UI
String? getName() {
return getFieldData<String>(fieldEnum: 'name');
}
DateTime? getBirthday() {
return getFieldData<DateTime>(fieldEnum: 'birthday')!;
}
void setName(String name) {
setFieldData(fieldEnum: 'name', data: name);
}
void setBirthday(DateTime birthday) {
setFieldData(fieldEnum: 'birthday', data: birthday);
}
///
}