flutter_form_bloc 0.3.0 copy "flutter_form_bloc: ^0.3.0" to clipboard
flutter_form_bloc: ^0.3.0 copied to clipboard

outdated

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

flutter_form_bloc #

Pub

Create Beautiful Forms in Flutter. The easiest way to Prefill, Validate, 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.

Example #

dependencies:
  form_bloc: ^0.4.0
  flutter_form_bloc: ^0.3.0
  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:

221
likes
0
pub points
92%
popularity

Publisher

unverified uploader

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

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

collection, flutter, flutter_bloc, form_bloc, keyboard_visibility, rxdart

More

Packages that depend on flutter_form_bloc