A simple alternative to the BLoC implementation created in Dimension C-137

Version

Getting started

You should ensure that you add the simple_bloc as a dependency in your flutter project.

read more at how to install

Usage

Simple BLoC for counter app


class CounterBloc extends Bloc {
  //define the controller
  final _counterController = BlocController<int>(initalData: 0);

  //output
  Stream<int> get counterOut => _counterController.stream;

  //action
  Action get increment => _counterController.action((value) {
        //implement your business logic here
        return ++value;
      });

  @override
  void dispose() {
    //dispose your controller
    _counterController.dispose();
  }
}

Screen Widget

import 'package:flutter/material.dart';
import 'package:simple_bloc/simple_bloc.dart';
import 'counter_bloc.dart';

class CounterScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //get bloc form provider
    final bloc = BlocProvider.of<CounterBloc>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("Simple BLoC"),
      ),
      body: Center(
        //consume output
        child: StreamBuilder(
          stream: bloc.counterOut,
          builder: (_, snapshot) {
            return Text(snapshot.data.toString());
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        //call bloc action
        onPressed: bloc.increment,
      ),
    );
  }
}

checkout app source at github

Libraries

simple_bloc