built_bloc_generator 0.2.4-dev copy "built_bloc_generator: ^0.2.4-dev" to clipboard
built_bloc_generator: ^0.2.4-dev copied to clipboard

outdated

Generates the BLoC boilerplate.

built_bloc_generator #

Generate the BLoC pattern boilerplate.

Quickstart #

In order to generate your bloc, your class must extend Bloc, be annotated with @bloc and with a mixin named _<class name>.

Then declare your subject fields and annotate them with @stream or @sink to generate a public getter accordingly.

You can also subscribe to a subject with the Listen annotation on a method.

import 'package:rxdart/rxdart.dart';
import 'package:built_bloc/built_bloc.dart';

part 'example.g.dart';

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

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

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

  @Listen("_add")
  void _onAdd(int value) {
    this._count.add(this._count.value + value);
  }

  @Listen("_reset")
  void _onReset() {
    this._count.add(0);
  }
}

This ExampleBloc will expose your streams and sinks.

final myBloc = ExampleBloc();

myBloc.count.listen((v) {
    print("count: $v");
})

myBloc.add.add(42);

How to use #

Install #

There are a few separate packages you need to install:

dependencies:
  built_bloc:

dev_dependencies:
  built_bloc_generator: 
  build_runner: 

Custom names #

To control how sink and stream getters are generated you can specify names by using @BlocStream("custom") / @BlocSink("custom") instead of @stream/@sink.

Both Sink and Stream #

If you want that a subject to be both exported sa Sink and Stream, you can add two annotations on a unique property.

By default, you sink will be renamed update<name>.

External listen #

By default, all Listen marked subscriptions aren't added to the subscriptions bloc's list since they are cancelled when their subject is closed.

If you want your subscription to be added to the subscriptions bloc list, you can set the external constructor parameter to true (@Listen("_reset", external: true)).

Run the generator #

To run the generator, you must use build_runner cli:

flutter pub pub run build_runner watch