From 3abdce8422faecee3c56c080650551484a6792e2 Mon Sep 17 00:00:00 2001 From: Renan <6718144+renancaraujo@users.noreply.github.com> Date: Tue, 28 Feb 2023 17:45:51 +0000 Subject: [PATCH] docs: add caching example (#78) * docs: add caching example --- README.md | 29 +++++++++++++++++++++++++++++ example/lib/main.dart | 15 ++++++++++----- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ef2bd15..589c09a 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,35 @@ void main() { } ``` + +## Caching validation results + +For cases where the validator method has an expensive implementation, one could cache the validation result on a `late final` field. + +```dart +import 'package:formz/formz.dart'; + +enum EmailValidationError { invalid } + +class Email extends FormzInput { + Email.pure([super.value = '']) : super.pure(); + + Email.dirty([super.value = '']) : super.dirty(); + + static final _emailRegExp = RegExp( + r'^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$', + ); + + late final validationResultCache = + _emailRegExp.hasMatch(value) ? null : EmailValidationError.invalid; + + @override + EmailValidationError? validator(String value) { + return validationResultCache; + } +} +``` + [ci_badge]: https://github.com/VeryGoodOpenSource/formz/actions/workflows/main.yaml/badge.svg [ci_link]: https://github.com/VeryGoodOpenSource/formz/actions [coverage_badge]: https://raw.githubusercontent.com/VeryGoodOpenSource/formz/main/coverage_badge.svg diff --git a/example/lib/main.dart b/example/lib/main.dart index fe0d0c8..2cd1052 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -163,10 +163,10 @@ class _MyFormState extends State { class MyFormState with FormzMixin { MyFormState({ - this.email = const Email.pure(), + Email? email, this.password = const Password.pure(), this.status = FormzSubmissionStatus.initial, - }); + }) : email = email ?? Email.pure(); final Email email; final Password password; @@ -191,16 +191,20 @@ class MyFormState with FormzMixin { enum EmailValidationError { invalid } class Email extends FormzInput { - const Email.pure([super.value = '']) : super.pure(); - const Email.dirty([super.value = '']) : super.dirty(); + Email.pure([super.value = '']) : super.pure(); + + Email.dirty([super.value = '']) : super.dirty(); static final _emailRegExp = RegExp( r'^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$', ); + late final validationResultCache = + _emailRegExp.hasMatch(value) ? null : EmailValidationError.invalid; + @override EmailValidationError? validator(String value) { - return _emailRegExp.hasMatch(value) ? null : EmailValidationError.invalid; + return validationResultCache; } } @@ -208,6 +212,7 @@ enum PasswordValidationError { invalid } class Password extends FormzInput { const Password.pure([super.value = '']) : super.pure(); + const Password.dirty([super.value = '']) : super.dirty(); static final _passwordRegex =