flutter_form_bloc 0.4.4

  • Readme
  • Changelog
  • Example
  • Installing
  • 83

flutter_form_bloc #

Pub

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.


To see complex examples, check out the example project.


Before to use this package you need to know the core concepts of bloc package and the basics of flutter_bloc


Widgets #

Note #

FormBloc, InputFieldBloc, TextFieldBloc, BooleanFieldBloc, SelectFieldBloc, 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.

Examples #

  • FieldBlocs with async validation: BLoC - UI.
  • Manually set FieldBloc error: BLoC - UI.
  • FormBloc with submission progress: BLoC - UI.
  • FormBloc without auto validation: BLoC - UI.
  • Complex async prefilled FormBloc: BLoC - UI.
  • And more examples.

Basic Example #

dependencies:
  form_bloc: ^0.5.2
  flutter_form_bloc: ^0.4.4
  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 #

1. 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:

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:

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')),
                    ),
                  ),
                ],
              ),
...          

Credits #

This package uses the following packages:

0.4.4 #

  • Dependencies Updates.
  • Fixed bug in suggestions of TextFieldBlocBuilder.
  • Added the next properties to TextFieldBlocBuilder.
    • hideOnLoadingSuggestions = false,
    • hideOnEmptySuggestions = false,
    • hideOnSuggestionsError = false,
    • loadingSuggestionsBuilder,
    • suggestionsNotFoundBuilder,
    • suggestionsErrorBuilder,
    • keepSuggestionsOnLoading = false,
    • showSuggestionsWhenIsEmpty = true,

0.4.3 #

  • Updated to form_bloc: ^0.5.2.
  • Documentation Updates.

0.4.2 #

  • Updated to form_bloc: ^0.5.1.

0.4.1+1 #

  • Documentation Updates.

0.4.1 #

  • FormBlocListener improved.

0.4.0+1 #

  • Documentation Updates.

0.4.0 #

  • Documentation Updates.
  • Updated to form_bloc: ^0.5.0.
  • Added more examples.

0.3.1 #

  • Documentation Updates.

0.3.0 #

  • Documentation Updates.
  • Updated to form_bloc: ^0.4.1.
  • Added CheckBoxGroupFieldBlocBuilder.
  • Added more examples.

0.2.1 #

  • Updated to form_bloc: ^0.3.1.

0.2.0 #

  • Dependencies and Documentation Updates.
  • Add RadioButtonGroupFieldBlocBuilder (#1).
  • Add Form with progress example.

0.1.0 #

Initial Version of the library.

example/README.md

Example #

To see the code, check out the forms folder.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_form_bloc: ^0.4.4

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_form_bloc/flutter_form_bloc.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
71
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
83
Learn more about scoring.

We analyzed this package on Oct 15, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.1
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Maintenance issues and suggestions

Support latest dependencies. (-10 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency (bloc).

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.2 <3.0.0
bloc ^0.15.0 0.15.0 0.16.0
collection ^1.14.11 1.14.11 1.14.12
flutter 0.0.0
flutter_bloc ^0.21.0 0.21.0
flutter_keyboard_visibility ^0.7.0 0.7.0
form_bloc ^0.5.2 0.5.2
rxdart ^0.22.1+1 0.22.3
Transitive dependencies
async 2.4.0
boolean_selector 1.0.5
charcode 1.1.2
equatable 0.6.1
matcher 0.12.5
meta 1.1.7
mockito 4.1.1
path 1.6.4
provider 3.1.0
quiver 2.0.5
sky_engine 0.0.99
source_span 1.5.5
stack_trace 1.9.3
stream_channel 2.0.0
string_scanner 1.0.5
term_glyph 1.1.0
test_api 0.2.8
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
pedantic ^1.7.0 1.8.0+1