Easy form building in Flutter with a fluent schema API.

Overview

former - Easy form building in Flutter

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 TextEditingControllers.
  • Validation and error handling requires imperative logic.

This is where former comes in.

Installation

Latest version: 0.2.0-dev.3

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:flutter_gen/flutter_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 with former so that it can be used by former 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 Providers in the context. Just make sure that the Providers 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 with Former.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(),
        ),
      ),
    );
  }
}

Source code

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.

Issues
  • Could not find the correct Provider<FormerProvider<FormerForm>> above the selector <FormerProvider<FormerForm>, String> Widget

    Could not find the correct Provider> above the selector , String> Widget

    This error happens to me when I try to add Former to my LoginPage. Could not find the correct Provider<FormerProvider<FormerForm>> above the selector <FormerProvider<FormerForm>, String> Widget

    Source code of my LoginPage below.

    login_page.dart:

    import 'package:flutter/material.dart';
    import 'package:flutter_i18n/flutter_i18n.dart';
    import 'package:former/former.dart';
    import 'package:learning_reddit_clone/pages/login_page/form_login.dart';
    import 'package:learning_reddit_clone/pages/login_page/login_form.dart';
    import 'package:learning_reddit_clone/widgets/header.dart';
    
    class LoginPage extends StatelessWidget {
      const LoginPage({
        Key? key,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: LayoutBuilder(
            builder: (context, constraints) {
              return Container(
                margin: EdgeInsets.symmetric(horizontal: constraints.maxWidth / 10),
                child: SingleChildScrollView(
                  child: SizedBox(
                    height: constraints.maxHeight,
                    child: Column(
                      children: [
                        Header(
                          title: FlutterI18n.translate(context, "pages.login.title"),
                        ),
                        Container(
                          child: Former(
                            form: () => LoginForm(),
                            schema: () => loginFormSchema,
                            child: FormLogin(),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
        );
      }
    }
    

    login_form.dart:

    import 'package:flutter/cupertino.dart';
    import 'package:former/validators.dart';
    import 'package:former_gen/former_gen.dart';
    import 'package:former/former.dart';
    
    part 'login_form.g.dart';
    
    class LoginForm = _LoginForm with _$LoginForm;
    
    @Formable()
    abstract class _LoginForm extends FormerForm {
      String email = '';
      String password = '';
    
      @override
      Future<void> submit(BuildContext context) {
        return Future.value();
      }
    }
    
    final loginFormSchema = LoginFormSchema(
      email: StringMust()..beAnEmail(),
      password: StringMust()..exist(),
    );
    

    form_login.dart:

    import 'package:flutter/material.dart';
    import 'package:flutter_i18n/flutter_i18n.dart';
    import 'package:former/former.dart';
    import 'package:learning_reddit_clone/pages/login_page/login_form.dart';
    
    class FormLogin extends StatefulWidget {
      const FormLogin({Key? key}) : super(key: key);
    
      @override
      _FormLoginState createState() => _FormLoginState();
    }
    
    class _FormLoginState extends State<FormLogin> {
      @override
      Widget build(BuildContext context) {
        return Column(
          children: [
            FormerTextField<LoginForm>(
              field: LoginFormField.email,
              keyboardType: TextInputType.emailAddress,
            ),
            FormerError(
              field: LoginFormField.email,
            ),
            FormerTextField<LoginForm>(
              field: LoginFormField.password,
              keyboardType: TextInputType.visiblePassword,
            ),
            FormerError(
              field: LoginFormField.password,
            ),
            ElevatedButton(
              onPressed: () => {},
              child: Text(
                FlutterI18n.translate(context, "pages.login.title"),
              ),
            ),
          ],
        );
      }
    }
    

    What can i do?

    opened by PiotrekPKP 2
  • v0.2.0 release

    v0.2.0 release

    Some tidying up before releasing 0.2.0.

    opened by kennethnym 1
  • Fix readme

    Fix readme

    Hi, I'm just checking out your project. Good work

    opened by rafalsobota 0
  • Make error messages more descriptive

    Make error messages more descriptive

    Make error messages more descriptive, making it easier to debug.

    Example: #2. The error message can suggest that the error may be due to missing generic type (which I think is a pretty common mistake).

    cc @PiotrekPKP

    enhancement good first issue 
    opened by kennethnym 0
  • Make provider error more descriptive

    Make provider error more descriptive

    Former widgets should show a helpful error message when the type of the form the widgets are consuming is not passed. For example:

    FormerTextField()
    

    should throw an AssertionError with a helpful error message:

    You must pass in the type of your form that this Former widget is consuming, so that the widget can locate and obtain the correct form.
    Example:
    
    FormerTextField<MyForm>(
                   ^^^^^^^^
                   Pass in the type of your form here.
    
      ...other params,
    ),
    
    This assertion is made by: FormerTextField.
    

    Closes #3

    cc @PiotrekPKP

    opened by kennethnym 0
Releases(v0.2.0)
  • v0.2.0(Aug 29, 2021)

  • v0.2.0-rc.1(Jun 3, 2021)

    TIL beta releases isn't considered later than dev releases on pub.dev. Since there will unlikely be breaking API changes in the near future, I decided to do an RC release.

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0-beta.1(May 30, 2021)

    After a month of internal testing (i.e. testing in my own project 😄 ), I decided to do a beta release. Note that this is a pre-release version, and things can change drastically from version to version.

    Nothing is changed from v0.2.0-dev.4 aside from more detailed docstring and new files for the doc site. For the full changelog since the initial release, refer to CHANGELOG.md.

    Any feedback is welcomed! 😄

    Source code(tar.gz)
    Source code(zip)
Owner
Kenneth
Self-taught developer for 6 years. Not quite good at it yet but I'll keep learning :)
Kenneth
Bhagavad Gita app using flutter & Bhagavad-Gita-API is A lightweight Node.js based Bhagavad Gita API [An open source rest api on indian Vedic Scripture Shrimad Bhagavad Gita].

Gita Bhagavad Gita flutter app. Download App - Playstore Web Application About Bhagavad Gita app using flutter & Bhagavad-Gita-API is A lightweight No

Ravi Kovind 7 Sep 29, 2021
Project demonstrates building a simple chat application using Flutter framework and Firebase cloud

Flutter Chat on Firebase Project demonstrates building a simple chat application using Flutter framework and Firebase cloud. App does not poll for new

Sukitha Udugamasooriya 7 Aug 14, 2021
Flutter Easy Getx Implementations .

Flutter Easy GetX Description People ask me how I manage state,dependency,routes etc when I work with flutter,Here is the Simple Brief About GetX whic

Tasnuva Tabassum oshin 13 Dec 6, 2021
An easy to use side menu in flutter and can used for navigations

Easy Sidemenu Easy sidemenu is An easy to use side menu (bar) for flutter that you can use for navigations in your application. Sidemenu is a menu tha

Mohammad Jamalianpour 16 Oct 7, 2021
Making Appwrite Authentication Easy

FlAppwrite Account Kit A Flutter wrapper for Appwrite's Accounts service, makes it easy to use manage authentication and account features. Under devel

Damodar Lohani 14 Jan 6, 2022
Flutter Cryptocurrency App with Riverpod & Freezed + Dio for API REST

Flutter Crypto APP Complete Flutter Application with Riverpod & Freezed + Dio for API REST. Features API REST (CryptoWatch) Linear Graph View (Hour, D

Salvador Valverde 181 Jan 16, 2022
This repository is Online_Learning Screen UI - Flutter. I am fetching the data from the local JSON API.

online_learning A new Flutter Online_Learning application. Designed by Arun PP, Code with Flutter by Kishor Kc. Kishor Kc I am fetching the data from

Kishor Kc 13 Dec 4, 2021
Authentication API client with Flutter (Login, Register, Google Login, Facebook Login, Apple Login)

Flutter Auth App (Login, Register, Google Login, Facebook Login, Apple Login) To use this client, get the server up and running. Try it out now! App S

Denzel Giraldo 18 Jan 8, 2022
A Flutter application with proper navigation and routes handling and API data fetching and posting.

Flutter-Navigation-and-API-Integration A Flutter application with proper navigation and routes handling and API data fetching and posting. ⏮ Preview G

Ehmad Saeed⚡ 7 Sep 18, 2021
A News App in Flutter using the newsapi.org API and using Bloc.

flutter_newsapp A News App using API from newsapi.org and using Bloc. Working ⚡ Screenshots =>=> ⚡ video Before Running Replace the <API_KEY> in lib/r

Arunoday kumar 10 Nov 27, 2021
Create a Flutter User Profile Page UI where you can access and edit your user's information within your Flutter app.

Flutter Tutorial - User Profile Page UI 1/2 Create a Flutter User Profile Page UI where you can access and edit your user's information within your Fl

Johannes Milke 22 Jan 9, 2022
Create a Flutter User Profile Page UI where you can access and edit your user's information within your Flutter app.

Flutter Tutorial - User Profile Page UI #2 Create a Flutter User Profile Page UI where you can access and edit your user's information within your Flu

Johannes Milke 15 Dec 20, 2021
Let's create a selectable Flutter Navigation Drawer with routing that highlights the current item within the Flutter Sidebar Menu.

Flutter Tutorial - Sidebar Menu & Selectable Navigation Drawer Let's create a selectable Flutter Navigation Drawer with routing that highlights the cu

Johannes Milke 9 Dec 9, 2021
Components that optimize Flutter fluency.(Flutter 流畅度优化的通用方案,轻松解决卡顿问题)

Flutter fluency optimization component "Keframe" Page switching fluency improved: How to use Project depend on: Quick learning Constructor Description

Ke Technologies 552 Jan 15, 2022
Challenge yourself every weekend with flutter. Join me to implement challenging UI & digital designs using Flutter.

Weekend With Flutter This is my new challenge. Every weekend, I want to implement challenging UI & digital designs using Flutter. you can join me with

Payam Zahedi 15 Jan 9, 2022
Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's information in Flutter.

Flutter Tutorial - User Profile & SharedPreferences Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's inf

Johannes Milke 12 Jan 11, 2022
Let's create a Flutter Collapsible Sidebar Menu that can collapse and expand the Navigation Drawer in Flutter.

Flutter Tutorial - Collapsible Sidebar Menu & Navigation Drawer Let's create a Flutter Collapsible Sidebar Menu that can collapse and expand the Navig

Johannes Milke 11 Dec 9, 2021
🚗 Apple CarPlay for Flutter Apps. Aims to make it safe to use apps made with Flutter in the car by integrating with CarPlay.

CarPlay with Flutter ?? Flutter Apps now on Apple CarPlay! flutter_carplay aims to make it safe to use iPhone apps made with Flutter in the car by int

Oğuzhan Atalay 91 Jan 11, 2022