Bloc Usage with RxDart in Flutter



abstract class CounterEvent {}

class IncrementEvent extends CounterEvent{}
class DecrementEvent extends CounterEvent{}

Bloc class

class CounterBlocRxDart extends Bloc {
  int _counter = 0;
  final _replaySubject = BehaviorSubject<int>();

  Stream<int> get counterStream =>;
  final _counterEventSubject = BehaviorSubject<CounterEvent>();

  Sink<CounterEvent> get counterEventSink => _counterEventSubject.sink;

  CounterBlocRxDart() {

  void _mapEventToState(CounterEvent event) {
    if (event is IncrementEvent)

  void dispose() {


class _MyHomePageState extends State<MyHomePage> {
  final _bloc = new CounterBlocRxDart();

  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the method, and use it to set our appbar title.
        title: Text(widget.title),
      body: Center(
          // Center is a layout widget. It takes a single child and positions it
          // in the middle of the parent.
          child: StreamBuilder(
            stream: _bloc.counterStream,
            builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                return Center(child: CircularProgressIndicator(),);
              return Column(
                children: <Widget>[Text('${}')],
      floatingActionButton: FloatingActionButton(
        onPressed: () => _bloc.counterEventSink.add(IncrementEvent()),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.

  void dispose() {

© 2019 All rights reserved. Codesenior.COM