Valform

Valform

Boilerplate-free form validation library.

Why?

There is no clean and nice way to separate business logic (validation) from presentation.

Why not Formz?

Formz defies Flutter’s way to handle state, forcing user to hold form state entirely in business logic.

But it can’t be done in Flutter. State is inevitably stored in TextEditingControllers. Formatters are applied inside widget itself.

When I use formz, I always find myself copy-pasting form inputs and struggling with simple use cases.

Why Valform?

  • Minimalistic.
  • Perfectly fits flutter’s form handling system.
  • Your teammates just need to explore a couple of simple concepts.

Simple Usage

Use case: We want to validate that email doesn’t exist in our database. If it does, display error.

For this case I will use VfReproduce, because I want to keep an error, if user accidentally enters previously validated email.

class LoginFormState extends ChangeNotifier {
  VfReproduce _emailAlreadyExists;

  LoginFormState([
    this._emailAlreadyExists = const VfReproduce.sealed()
  ]);

  String? validateEmail(String? email) {
    if (_emailAlreadyExists.access(email)) {
      return "Email already exists";
    }

    return null;
  }

  Future<void> submit() {
    await Future.delayed(Duration(seconds: 1)); // access the database
    _emailAlreadyExists = VfReproduce();
    notifyListeners();
  }
}

Somewhere in Flutter code:

final loginFormState = LoginFormState();

void initState() {
  super.initState();
  loginFormState.addListener(() => setState(() {}));
}

Widget build(BuildContext context) => Column(
  children: [
    TextFormField(
      validator: loginFormState.validateEmail,
    ),
    OutlinedButton(onPressed: loginFormState.submit),
  ]
);

Inspiration

The whole work was inspired by event concept in async_redux, created by Marcelo Glasberg.

GitHub

View Github