Skip to content
Generate the BLoC pattern boilerplate.
Dart Java Objective-C
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
built_bloc
built_bloc_generator Downgraded meta for Flutter compatibility. May 22, 2019
flutter_built_bloc Downgraded meta for Flutter compatibility. May 22, 2019
.gitignore
LICENSE
README.md
publish.dart Added specific flutter features. Jan 25, 2019

README.md

built_bloc

Generate the BLoC pattern boilerplate.

Why ?

After using the BLoC pattern a little, it seems pretty cool for sharing code and separation of concerns, but I quickly found myself to write a lot of repetitive boilerplate code : I felt the need for a generator to assist me.

Here is a simple vanilla bloc example which obviously highlights repeated patterns while declaring subjects, streams, sinks and subscriptions.

class VanillaExampleBloc {

  Sink<void> get reset => this._reset.sink;

  Sink<int> get add => this._add.sink;

  Stream<int> get count => this._count.stream;

  final PublishSubject<int> _add = PublishSubject<int>();

  final PublishSubject<void> _reset = PublishSubject<void>();

  final BehaviorSubject<int> _count = BehaviorSubject<int>.seeded(0);

  List<StreamSubscription> subscriptions;

  List<Subject> subjects;

  VanillaExampleBloc() {
    subscriptions = [
      this._add.listen(_onAdd),
      this._reset.listen(_onReset),
    ];
    subjects = [
      this._add,
      this._count,
      this._reset,
    ];
  }

  void _onAdd(int value) {
    this._count.add(this._count.value + value);
  }

  void _onReset(int value) {
    this._count.add(0);
  }

  @mustCallSuper
  void dispose() {
    this.subjects.forEach((s) => s.close());
    this.subscriptions.forEach((s) => s.cancel());
  }
}

With built_bloc, you can replace all of that with just a few lines of code :

@bloc
class ExampleBloc extends Bloc with _ExampleBloc {
  @stream
  final BehaviorSubject<int> _count = BehaviorSubject<int>(seedValue: 0);

  @sink
  @Bind("_onAdd")
  final PublishSubject<int> _add = PublishSubject<int>();

  @sink
  @Bind("_onReset")
  final PublishSubject<void> _reset = PublishSubject<void>();

  void _onAdd(int value) {
    this._count.add(this._count.value + value);
  }

  void _onReset() {
    this._count.add(0);
  }
}

How to use ?

See the built_bloc_generator package.

You can’t perform that action at this time.