Flutter FormX
Flutter FormX is an extensible package to make it easy to build, react to and validate forms using MobX and Bloc.
Features
- Responsive state and form answer caching on current instance.
- Form validation.
- Abstract ValidationResult and Validator classes to help you integrate with form builder and make your own validations.
Supported state management solutions
This library has built-in adapters for both MobX and Bloc as its state management solutions. However, you can use the vanilla implementation to adapt FormX to your favorite state management solution.
Validators
You can create any kind of validator specifically for your needs and according to the field
type you have. We've included the RequiredFieldValidator
, but feel free to create more in your
project as you need.
Create your own validators
You can do that by creating a class that extends the Validator
class. See example below:
Example:
class EmailValidator extends Validator<String?> {
final String errorMessage;
EmailValidator(this.errorMessage,);
@override
Future<ValidatorResult> validate(value) {
if (value == null || value.isEmpty) {
return result(isValid: true);
}
final isEmailValid = _validateEmail(value);
return result(
isValid: isEmailValid,
errorMessage: errorMessage,
);
}
bool _validateEmail(String email) {
final regex = RegExp(r'^[^@,\s]+@[^@,\s]+\.[^@,.\s]+$');
return regex.hasMatch(email);
}
}
Note
We recommend that you avoid implementing more than one validation in each validator. If the field must be required and a valid email, add two validators, such asRequiredValidator(), EmailValidator()
. This way you can reuse the email validator if this field ever becomes optional.
Expanding the library
Feel free to expand the library and make it compatible with other state management solutions. When
doing that, keep in mind you'll need to
implement FormXAdapter<T>
.
If you don't know how to do it, please take a look at the
other adapters'
implementations. Also, know you can count on our support with that!
Just open an issue or PR and we'll be happy to help.
Testing
See example/test for testing examples.