flutter_form_bloc 0.1.0

flutter_form_bloc #

Pub

A Flutter package with flutter widgets that helps to create forms with form_bloc package.


To see complex examples check 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, TextFieldBloc, SelectFieldBloc, and BooleanFieldBloc are blocs, so you can use BlocBuilder or BlocListener of flutter_bloc for make any widget you want compatible with any FieldBloc.

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

Example #

dependencies:
  form_bloc: ^0.2.0
  flutter_form_bloc: ^0.1.0
  flutter_bloc: ^0.20.1
import 'package:form_bloc/form_bloc.dart';

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

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

  @override
  Stream<FormBlocState<String, String>> onSubmitting() async* {
    // Login logic...
    await Future<void>.delayed(Duration(seconds: 2));
    yield currentState.toSuccess();
  }
}
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 SimpleLoginForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<SimpleLoginFormBloc>(
      builder: (context) => SimpleLoginFormBloc(),
      child: Builder(
        builder: (context) {
          final formBloc = BlocProvider.of<SimpleLoginFormBloc>(context);

          return Scaffold(
            appBar: AppBar(title: Text('Simple login')),
            body: FormBlocListener<SimpleLoginFormBloc, 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<String>(
                    textFieldBloc: formBloc.emailField,
                    formBloc: formBloc,
                    errorBuilder: (context, error) => error,
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                      labelText: 'Email',
                      prefixIcon: Icon(Icons.email),
                    ),
                  ),
                  TextFieldBlocBuilder<String>(
                    textFieldBloc: formBloc.passwordField,
                    formBloc: formBloc,
                    errorBuilder: (context, error) => error,
                    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 SimpleLoginFormBloc will be String.

import 'package:form_bloc/form_bloc.dart';

class SimpleLoginFormBloc 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 SimpleLoginFormBloc will have two TextFieldBloc<String>, so the Error type will be String, and the validators must return a error of String type.

import 'package:form_bloc/form_bloc.dart';

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

}

3. Implement the get method fieldBlocs #

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

For example the SimpleLoginFormBloc must return a List with emailField and passwordField.

import 'package:form_bloc/form_bloc.dart';

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

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

4. Implement the method onSubmitting #

onSubmitting return a Stream<FormBlocState<SuccessResponse, FailureResponse>> and will called when the form is submitting.

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

You can yield a new state using:

For example onSubmitting of LoginFormBloc will return a Stream<FormBlocState<String, String>> and yield currentState.toSuccess().

import 'package:form_bloc/form_bloc.dart';

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

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

  @override
  Stream<FormBlocState<String, String>> onSubmitting() async* {
    // Login logic...
    await Future<void>.delayed(Duration(seconds: 2));
    yield currentState.toSuccess();
  }
}

5. 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 SimpleLoginForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<SimpleLoginFormBloc>(
      builder: (context) => SimpleLoginFormBloc(),
      child: Builder(
        builder: (context) {
          final formBloc = BlocProvider.of<SimpleLoginFormBloc>(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<SimpleLoginFormBloc, 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<String> for connect with emailField and passwordField of SimpleLoginFormBloc.

...
              child: ListView(
                children: <Widget>[
                  TextFieldBlocBuilder<String>(
                    textFieldBloc: formBloc.emailField,
                    formBloc: formBloc,
                    errorBuilder: (context, error) => error,
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                      labelText: 'Email',
                      prefixIcon: Icon(Icons.email),
                    ),
                  ),
                  TextFieldBlocBuilder<String>(
                    textFieldBloc: formBloc.passwordField,
                    formBloc: formBloc,
                    errorBuilder: (context, error) => error,
                    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.1.0 #

Initial Version of the library.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_form_bloc_example/bloc_delegate.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_form_bloc_example/forms/complex_async_prefilled_form.dart';
import 'package:flutter_form_bloc_example/forms/complex_login_form.dart';
import 'package:flutter_form_bloc_example/forms/simple_async_prefilled_form.dart';
import 'package:flutter_form_bloc_example/forms/simple_login_form.dart';
import 'package:flutter_form_bloc_example/forms/simple_register_form.dart';
import 'package:flutter_form_bloc_example/styles/themes.dart';
import 'package:flutter_form_bloc_example/widgets/widgets.dart';

void main() {
  BlocSupervisor.delegate = SimpleBlocDelegate();
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: Themes.formTheme,
      routes: {
        '/': (context) => Home(),
        '/success': (context) => SuccessScreen(),
      },
    ),
  );
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Form BLoC Example'),
        elevation: 2,
      ),
      body: ListView.separated(
        separatorBuilder: (_, __) => Divider(height: 1),
        itemCount: Form.forms.length,
        itemBuilder: (context, index) => ListItem(index, Form.forms[index]),
      ),
    );
  }
}

class ListItem extends StatelessWidget {
  final int index;
  final Form form;
  const ListItem(this.index, this.form, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Container(
        height: 28,
        child: CircleAvatar(
          backgroundColor: Theme.of(context).iconTheme.color,
          child: Text(
            '${index + 1}',
            style: TextStyle(
              color: Theme.of(context).scaffoldBackgroundColor,
            ),
          ),
        ),
      ),
      isThreeLine: true,
      title: Text(form.title),
      subtitle: Text(
        form.description,
        maxLines: 3,
        overflow: TextOverflow.ellipsis,
      ),
      onTap: () => Navigator.of(context)
          .push<void>(MaterialPageRoute(builder: (_) => form.widget)),
    );
  }
}

class Form {
  final String title;
  final String description;
  final Widget widget;

  Form(this.title, this.description, this.widget);

  static List<Form> forms = [
    Form(
      'Simple login',
      'Stateless, validators, text fields, and success response.',
      SimpleLoginForm(),
    ),
    Form(
      'Complex login',
      'Text field with used emails suggestions (delete on long press), dropdown field, focus nodes, and multiple responses.',
      ComplexLoginForm(),
    ),
    Form(
      'Simple register',
      'Focus nodes, complex validators, text fields, check box field, and success response.',
      SimpleRegisterForm(),
    ),
    Form(
      'Simple Async prefilled form',
      'Prefilled form with async data like Shared Preferences.',
      SimpleAsyncPrefilledForm(),
    ),
    Form(
      'Complex Async prefilled form',
      'Prefilled form with async data (like API fetch), and retry when fail to load.',
      ComplexAsyncPrefilledForm(),
    ),
  ];
}

Use this package as a library

1. Depend on it

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


dependencies:
  flutter_form_bloc: ^0.1.0

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]
23
Health:
Code health derived from static analysis. [more]
94
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
56
Learn more about scoring.

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

  • Dart: 2.4.0
  • pana: 0.12.19
  • Flutter: 1.7.8+hotfix.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Fix lib/src/dropdown.dart. (-5.84 points)

Analysis of lib/src/dropdown.dart reported 12 hints, including:

line 34 col 8: Don't import implementation files from another package.

line 35 col 8: Don't import implementation files from another package.

line 36 col 8: Don't import implementation files from another package.

line 37 col 8: Don't import implementation files from another package.

line 38 col 8: Don't import implementation files from another package.

Maintenance issues and suggestions

Support latest dependencies. (-20 points)

The version constraint in pubspec.yaml does not support the latest published versions for 2 dependencies (collection, flutter_bloc).

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
collection ^1.14.11 1.14.11 1.14.12
flutter 0.0.0
flutter_bloc ^0.20.1 0.20.1 0.21.0
form_bloc ^0.2.0 0.2.0
keyboard_visibility ^0.5.1 0.5.6
rxdart ^0.22.1+1 0.22.1+1
Transitive dependencies
bloc 0.14.4 0.15.0
equatable 0.4.0
meta 1.1.6 1.1.7
provider 3.1.0
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test