Easy Form State Management using BLoC pattern – Create Beautiful Forms in Flutter

flutter_form_bloc

Create Beautiful Forms in Flutter. The easiest way to Prefill, Async Validation, Update Form Fields, and Show Progress, Failures, Successes or Navigate by Reacting to the Form State.

Separate the Form State and Business Logic from the User Interface using form_bloc.

Widgets

  • TextFieldBlocBuilder: A material design text field that can show suggestions.
  • DropdownFieldBlocBuilder: A material design dropdown.
  • RadioButtonGroupFieldBlocBuilder: A material design radio buttons.
  • CheckboxFieldBlocBuilder: A material design checkbox.
  • CheckboxGroupFieldBlocBuilder: A material design checkboxes.
  • FormBlocListener: BlocListener that reacts to the state changes of the FormBloc.

Note

FormBloc, InputFieldBloc, TextFieldBloc, BooleanFieldBloc, SelectFildBloc, MultiSelectFieldBloc are blocs, so you can use BlocBuilder or BlocListener of flutter_bloc for make any widget you want compatible with any FieldBloc or FormBloc.

If you want me to add other widgets please let me know, or make a pull request.

Basic Example

dependencies:
  form_bloc: ^0.5.1
  flutter_form_bloc: ^0.4.2
  flutter_bloc: ^0.21.0
import 'package:form_bloc/form_bloc.dart';

class LoginFormBloc extends FormBloc<String, String> {
  final emailField = TextFieldBloc(validators: [Validators.email]);
  final passwordField = TextFieldBloc();

  final UserRepository _userRepository;

  LoginFormBloc(this._userRepository);

  @override
  List<FieldBloc> get fieldBlocs => [emailField, passwordField];

  @override
  Stream<FormBlocState<String, String>> onSubmitting() async* {
    try {
      _userRepository.login(
        email: emailField.value,
        password: passwordField.value,
      );
      yield currentState.toSuccess();
    } catch (e) {
      yield currentState.toFailure();
    }
  }
}
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_bloc/flutter_form_bloc.dart';
import 'package:flutter_form_bloc_example/forms/simple_login_form_bloc.dart';
import 'package:flutter_form_bloc_example/widgets/widgets.dart';

class LoginForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<LoginFormBloc>(
      builder: (context) =>
          LoginFormBloc(RepositoryProvider.of<UserRepository>(context)),
      child: Builder(
        builder: (context) {
          final formBloc = BlocProvider.of<LoginFormBloc>(context);

          return Scaffold(
            appBar: AppBar(title: Text('Simple login')),
            body: FormBlocListener<LoginFormBloc, String, String>(
              onSubmitting: (context, state) => LoadingDialog.show(context),
              onSuccess: (context, state) {
                LoadingDialog.hide(context);
                Navigator.of(context).pushReplacementNamed('success');
              },
              onFailure: (context, state) {
                LoadingDialog.hide(context);
                Notifications.showSnackBarWithError(
                    context, state.failureResponse);
              },
              child: ListView(
                children: <Widget>[
                  TextFieldBlocBuilder(
                    textFieldBloc: formBloc.emailField,
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                      labelText: 'Email',
                      prefixIcon: Icon(Icons.email),
                    ),
                  ),
                  TextFieldBlocBuilder(
                    textFieldBloc: formBloc.passwordField,
                    suffixButton: SuffixButton.obscureText,
                    decoration: InputDecoration(
                      labelText: 'Password',
                      prefixIcon: Icon(Icons.lock),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: RaisedButton(
                      onPressed: formBloc.submit,
                      child: Center(child: Text('LOGIN')),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

Basic usage

Import it

import ‘package:form_bloc/form_bloc.dart’;

2. Create a class that extends FormBloc<SuccessResponse, FailureResponse>

FormBloc<SuccessResponse, FailureResponse>

SuccessResponse The type of the success response.

FailureResponse The type of the failure response.

For example, the SuccessResponse type and FailureResponse type of LoginFormBloc will be String.

import ‘package:form_bloc/form_bloc.dart’;

class LoginFormBloc extends FormBloc<String, String> {}

2. Create Field Blocs

You need to create field blocs, and these need to be final.

You can create:

  • InputFieldBloc<Value>.
  • TextFieldBloc.
  • BooleanFieldBloc.
  • SelectFieldBloc<Value>.
  • MultiSelectFieldBloc<Value>.

For example the LoginFormBloc will have two TextFieldBloc.

import ‘package:form_bloc/form_bloc.dart’;

class LoginFormBloc extends FormBloc<String, String> {

  final emailField = TextFieldBloc(validators: [Validators.email]);

  final passwordField = TextFieldBloc();

}

3. Add Services/Repositories

In this example we need a UserRepository for make the login.

import ‘package:form_bloc/form_bloc.dart’;

class LoginFormBloc extends FormBloc<String, String> {

  final emailField = TextFieldBloc(validators: [Validators.email]);

  final passwordField = TextFieldBloc();

  final UserRepository _userRepository;

  LoginFormBloc(this._userRepository);

}

4. Implement the get method fieldBlocs

You need to override the get method fieldBlocs and return a list with all FieldBlocs.

For example the LoginFormBloc need to return a List with emailField and passwordField.

import ‘package:form_bloc/form_bloc.dart’;

class LoginFormBloc extends FormBloc<String, String> {

  final emailField = TextFieldBloc(validators: [Validators.email]);

  final passwordField = TextFieldBloc();

  final UserRepository _userRepository;

  LoginFormBloc(this._userRepository);

  @override

  List<FieldBloc> get fieldBlocs => [emailField, passwordField];

}

5. Implement onSubmitting method

onSubmitting returns a Stream<FormBlocState<SuccessResponse, FailureResponse>>.

This method is called when you call loginFormBloc.submit() and FormBlocState.isValid is true, so each field bloc has a valid value.

You can get the current value of each field bloc calling emailField.value or passwordField.value.

You must call all your business logic of this form here, and yield the corresponding state.

You can yield a new state using:

  • currentState.toFailure([FailureResponse failureResponse]).
  • currentState.toSuccess([SuccessResponse successResponse]).
  • currentState.toLoaded().

See other states here.

For example onSubmitting of LoginFormBloc will return a Stream<FormBlocState<String, String>> and yield currentState.toSuccess() if the _userRepository.login method not throw any exception, and yield “currentState.toFailure()` if throw a exception.

import ‘package:form_bloc/form_bloc.dart’;

class LoginFormBloc extends FormBloc<String, String> {

  final emailField = TextFieldBloc(validators: [Validators.email]);

  final passwordField = TextFieldBloc();

  final UserRepository _userRepository;

  LoginFormBloc(this._userRepository);

  @override

  List<FieldBloc> get fieldBlocs => [emailField, passwordField];

  @override

  Stream<FormBlocState<String, String>> onSubmitting() async* {

    try {

      _userRepository.login(

        email: emailField.value,

        password: passwordField.value,

      );

      yield currentState.toSuccess();

    } catch (e) {

      yield currentState.toFailure();

    }

  }

}

6. Create a Form Widget

You need to create a widget with access to the FormBloc.

In this case I will use BlocProvider for do it.

class LoginForm extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return BlocProvider<LoginFormBloc>(

      builder: (context) =>

          LoginFormBloc(RepositoryProvider.of<UserRepository>(context)),

      child: Builder(

        builder: (context) {

          final formBloc = BlocProvider.of<LoginFormBloc>(context);

          return Scaffold();

        },

      ),

    );

  }

}

6. Add FormBlocListener for manage form state changes

You need to add a FormBlocListener.

In this example:

  • I will show a loading dialog when the state is loading.
  • I will hide the dialog when the state is success, and navigate to success screen.
  • I will hide the dialog when the state is failure, and show a snackBar with the error.

          return Scaffold(

            appBar: AppBar(title: Text(‘Simple login’)),

            body: FormBlocListener<LoginFormBloc, String, String>(

              onSubmitting: (context, state) => LoadingDialog.show(context),

              onSuccess: (context, state) {

                LoadingDialog.hide(context);

                Navigator.of(context).pushReplacementNamed(‘success’);

              },

              onFailure: (context, state) {

                LoadingDialog.hide(context);

                Notifications.showSnackBarWithError(

                    context, state.failureResponse);

              },

              child:

              ),

            ),

          );

         

6. Connect the Field Blocs with Field Blocs Builder

In this example I will use TextFieldBlocBuilder for connect with emailField and passwordField of LoginFormBloc.

              child: ListView(

                children: <Widget>[

                  TextFieldBlocBuilder(

                    textFieldBloc: formBloc.emailField,

                    keyboardType: TextInputType.emailAddress,

                    decoration: InputDecoration(

                      labelText: ‘Email’,

                      prefixIcon: Icon(Icons.email),

                    ),

                  ),

                  TextFieldBlocBuilder(

                    textFieldBloc: formBloc.passwordField,

                    suffixButton: SuffixButton.obscureText,

                    decoration: InputDecoration(

                      labelText: ‘Password’,

                      prefixIcon: Icon(Icons.lock),

                    ),

                  ),

                ],

              ),

         

7. Add a widget for submit the FormBloc

In this example I will add a RaisedButton and pass submit method of FormBloc to submit the form.

              child: ListView(

                children: <Widget>[

                  …,

                  Padding(

                    padding: const EdgeInsets.all(8.0),

                    child: RaisedButton(

                      onPressed: formBloc.submit,

                      child: Center(child: Text(‘LOGIN’)),

                    ),

                  ),

                ],

              ),

         

Source Credit Url – Github Code