former – easy form building in flutter
easy form building in flutter with a fluent schema api.
motivation
formik is one of my favorite react libraries. it is a form library that drastically reduces
boilerplate for keeping track of field values, validation, and form submission.
form building in flutter suffers from similar issues:
- developers have to manually keep track of field values, for example using
texteditingcontroller
s. - validation and error handling requires imperative logic.
this is where former
comes in.
installation
latest version: 0.2.0-rc.1
note: this package is at a pre-release stage – api can change drastically in the future.
add former
to the dependencies
section of your pubspec.yaml
:
dependencies:
# ...your other dependencies
former: # optionally lock-in a version
and add former_gen
to the dev_dependencies
section:
dev_dependencies:
# ...your other dependencies
former_gen: # optionally lock-in a version
finally, run flutter pub get
.
features
former
provides the following features:
- enabling/disabling form globally
- declarative form validation
- automatic value tracking via
former
widgets - easy error handling with
formererror
widget. - type-safe access of form.
usage
creating the form
former
works by inspecting your form class and generating the corresponding code that makes it work with the former
api.
first, lets create our form class in my_form.dart
:
import 'package:former_gen/former_gen.dart';
@formable()
abstract class _myform extends formerform {
}
a couple of things to note:
- the form class is abstract and private. this is because some logic has to be mixed in before it is usable by
former
. - the form class extends
formerform
. it interfaces our form class withformer
so that it can be used byformer
internals.
the formerform
requires subclasses to implement the bracket operators. this is not needed in our abstract class
because that burden will be handled by former
‘s code generation. we only need to implement the submit
method. for
example, it can include submitting your form to some api for further processing.
for simplicity’s sake, our implementation of submit
only returns an empty future value.
notice that the submit
method
accepts a buildcontext
. this is the same buildcontext
used by the former
widget that we will use later
to provide this form. it can come in handy when you want to access other provider
s in the context. just make sure that
the provider
s you want to access are parents of the former
widget that is providing the form.
@formable()
abstract class _myform extends formerform {
@override
future<void> submit(buildcontext context) {
// todo: implement submit()
return future.value();
}
}
let’s also add some fields to our form:
@formable()
abstract class _myform extends formerform {
string username = '';
string email = '';
@override
future<void> submit(buildcontext context) {
// todo: implement submit()
return future.value();
}
}
our form class is not usable until we mix in the generated mixin which makes the form “indexable” with the bracket
operator, and also contain type information of the fields in the form. add the following before the class declaration:
class myform = _myform with _$myform;
…and add this:
part 'my_form.g.dart';
to import the generated code.
the dart analyzer will complain about unrecognized symbols and imports. to fix it, start the code generation
via build_runner
:
flutter pub run build_runner build
specifying the requirements
imagine that our form has the following requirements:
- the username should be at least 10 characters long, but not longer than 50 characters.
- the email field, well, should contain a valid email.
without former
, this has to be done in an imperative way by, for example, checking the length of the string.
former
‘s super declarative api for specifying requirements makes everything easy and readable. all you have to do is
to create the schema class that is generated for you. in my_form.dart
,
final schema = myformschema(
username: stringmust()
..hasminlength(10)
..hasmaxlength(50),
email: stringmust()
..beanemail(),
);
as you can see, the api is very self-explanatory. note the use of the cascade operator ..
– in dart, instead of
returning this
for method chaining, the cascade operator ..
is preferred.
building form controls
former
exports various widgets that interacts with the given form. to start, let’s first create our form widget:
import 'package:flutter/material.dart';
import 'package:former/former.dart';
import 'my_form.dart';
class form extends statelesswidget {
@override
widget build() {
return column(
children: [
formertextfield<myform>(field: myformfield.username),
formertextfield<myform>(field: myformfield.email),
elevatedbutton(
onpressed: () {
former.of<myform>(context, listen: false).submit();
},
child: text('submit form')
)
],
);
}
}
our form contains two text fields that control the username
and the email
field respectively. the myformfield
class is automatically generated for you, so you don’t have to create one yourself.
when the button is clicked, myform
‘s submit
method is called to submit the form. beside submitting the
form, former.of(context)
gives you access to:
- the current form with
.form
. for example, you can access the current value of the username field
withformer.of<myform>(context).form.username
- enabling/disabling the form with
.isformenabled
getter/setter. when a form is disabled, all the former controls
controlling the form is automatically disabled as well. - the error of a given field with
.errorof(field)
which returns the error message as a result of a failed validation.
it returns an empty string when the field is valid, or when no validation is performed yet.
this is an extremely simplified version of a form to showcase the widgets. realistically, each former control should
have a label describing what they do. in the future, there may be a widget that attaches a label to a former control.
for now, it has to be done manually.
wrapping it all up
finally, all we have to do is to wrap our form widget with the former
widget:
import 'package:flutter/material.dart';
import 'package:former/former.dart';
import 'my_form.dart';
class myapp extends statelesswidget {
@override
widget build() {
return materialapp(
home: scaffold(
body: former(
form: () => myform(),
schema: () => schema, // exported from my_form.dart
child: _myform(),
),
),
);
}
}
the full source code is available in the example
folder.
api
available widgets
the following widgets are available for use with former
:
formertextfield
formercheckbox
formerswitch
formerslider
in development:
formerradio
formerdropdownbutton
schema
the following validators can be used to validate form fields. each validator has various methods that imposes extra
requirements on a given value (called requirement methods).
every requirement method accepts an optional error message param that is returned when the value does not meet that
requirement.
stringmust
numbermust
boolmust
implement the validator
class to create custom validation logic.
Comments are closed.