Install
This will add lo_form
to your package's pubspec.yaml
(and run an implicit dart pub get
):
flutter pub add lo_form
Simple Example
In this example, you will learn how to create a simple form for newsletter subscription, with a simple validation for the email field.
You can find the full code at the end if you don't want to go step-by-step.
-
Create
NewsletterForm
widget.import 'package:flutter/material.dart'; import 'package:lo_form/lo_form.dart'; class NewsletterForm extends StatelessWidget { @override Widget build(BuildContext context) { return Container(); } }
-
Design the form using
LoForm
widget as a wrapper andLo-*
widgets for fields. Note that each field must have a uniquename
that will be used to access it later.class NewsletterForm extends StatelessWidget { @override Widget build(BuildContext context) { return LoForm( builder: (form) { return Column( children: [ LoTextField( name: 'Email', ), const SizedBox(height: 32), ElevatedButton( onPressed: () {}, child: const Text('Subscribe'), ), ], ); }, ); } }
-
Add validation to the
Email
field:LoTextField( name: 'Email', validators: [ LoRequiredValidator(), LoRegExpValidator.email(), ], )
-
Implement what happens when the form is submitted, then return
true
if the submission completed successfully, orfalse
if something wrong happened:LoForm( onSubmit: (values, setErrors) { print('Welcome ${values.get('Email')}'); return true; }, builder: (form) { // Rest of code... }, )
-
Call the submit method using
form
variable:ElevatedButton( onPressed: form.submit, child: const Text('Subscribe'), )
-
Choose when the form can be submitted, by setting
submittableWhen
, this will disable the submit button whenever the status doesn't match.LoForm( submittableWhen: (status) => status.isValid, onSubmit: (values, setErrors) { // Rest of code... }, builder: (form) { // Rest of code... }, )
-
Full code:
import 'package:flutter/material.dart'; import 'package:lo_form/lo_form.dart'; class NewsletterForm extends StatelessWidget { @override Widget build(BuildContext context) { return LoForm( submittableWhen: (status) => status.isValid, onSubmit: (values, setErrors) { print('Welcome ${values.get('Email')}'); return true; }, builder: (form) { return Column( children: [ LoTextField( name: 'Email', validators: [ LoRequiredValidator(), LoRegExpValidator.email(), ], ), const SizedBox(height: 32), ElevatedButton( onPressed: form.submit, child: const Text('Subscribe'), ), ], ); }, ); } }
Advanced Example
For a more advanced example,
check the RegisterForm
widget that is used in the demo.