X
    Categories: Flutter

Flutter BLoC Pattern Implementation

 

Flutter BLoC :

Flutter BLoC (Business Logic Component) Implementation is the one of the architectural way to perform to maintain the app code.In general when we are developing a app it is better to follow a proper pattern which will be easier to manage.

BLoC pattern is recommended by Google for state management practices to handle the state from a single point to anywhere in the project.

Its also forms a bridge between database and widgets and update them when ever there is new data updated into databases.

When more than one developer is involved it is better to follow a good practice to follow because every developer can easily read the code and make changes.

BLoC pattern in flutter is explained in this part of the tutorial with a simple calculation example so that it is easy to understand.

 

Some of the benefits of using the Bloc pattern include:

Separation of concern:

The Bloc pattern implements seperation of content i.e., UI, business logic, and data persistence layers, which makes the code easier to understand and maintain.

Testability:

Testing is the important aspect, so as the business logic is separated from the UI, it is easier to write automated tests for the app.

Reusability:

The Bloc pattern promotes the code reuse of business logic components which can be used through out the app there after reduce development time and improve code quality.

Scalability:

Bloc pattern can be used to easily manage complex state in large apps, making it a good choice for scalable applications.

 

Flutter BLoC Video Tutorial :

Go through the below tutorial for more detailed information on BLoC implementation.

 

Project Structure :

This image depicts project structure for flutter bloc implementation.

 

 

CalcEvent.dart :

Declare events for addition, subtraction, multiply & division also provide parameters.

abstract class CalcEvent{

  int a;
  int b;

  CalcEvent(this.a, this.b);
}

class AddEvent extends CalcEvent{
  AddEvent(int a, int b) : super(a, b);
}
class SubEvent extends CalcEvent{
  SubEvent(int a, int b) : super(a, b);
}
class MultiplyEvent extends CalcEvent{
  MultiplyEvent(int a, int b) : super(a, b);
}
class DivEvent extends CalcEvent{
  DivEvent(int a, int b) : super(a, b);
}

 

CalcBloc.dart :

Initialize integer variable result to zero.

int _result = 0;

 

Declare Sink and Stream’s for accepting data and providing output

 

final _calcStateController = StreamController<int>();

StreamSink<int> get _inCalc => _calcStateController.sink;

Stream<int> get calc => _calcStateController.stream;

final _calcEventController = StreamController<CalcEvent>();

Sink<CalcEvent> get calcEventSink => _calcEventController.sink;

 

Add a listener

CalcBloc() {

  _calcEventController.stream.listen(_mapEventToState);
}

 

Detect the event in terms of addition, subtraction, multiplication, divide.

void _mapEventToState(CalcEvent event) {
  if (event is AddEvent)
    _result =  event.a + event.b;
  else if (event is SubEvent)
    _result =  event.a - event.b;
  else if (event is MultiplyEvent)
    _result =  event.a * event.b;
  else
    _result =  (event.a / event.b).toInt();

  _inCalc.add(_result);
}

 

Dispose the controller after use

void dispose() {
  _calcStateController.close();
}

 

import 'dart:async';

import 'package:flutter_bloc/CalcEvent.dart';

class CalcBloc {
  int _result = 0;

  final _calcStateController = StreamController<int>();

  StreamSink<int> get _inCalc => _calcStateController.sink;

  Stream<int> get calc => _calcStateController.stream;

  final _calcEventController = StreamController<CalcEvent>();

  Sink<CalcEvent> get calcEventSink => _calcEventController.sink;

  CalcBloc() {

    _calcEventController.stream.listen(_mapEventToState);
  }

  void _mapEventToState(CalcEvent event) {
    if (event is AddEvent)
      _result =  event.a + event.b;
    else if (event is SubEvent)
      _result =  event.a - event.b;
    else if (event is MultiplyEvent)
      _result =  event.a * event.b;
    else
      _result =  (event.a / event.b).toInt();

    _inCalc.add(_result);
  }

  void dispose() {
    _calcStateController.close();
  }
}

 

 

main.dart :

Providing the source code for bloc implementation.

Start with void main()

void main() => runApp(MyApp());

 

Specify the MaterialApp

MaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: MyHomePage(title: 'Flutter Demo Home Page'),
);

 

Initialize the components

final _bloc = CalcBloc();
TextEditingController fieldA = new TextEditingController();
TextEditingController fieldB = new TextEditingController();

 

Declare TextFields to accept inputs

TextField(
    controller: fieldA,
    keyboardType: TextInputType.number,
    decoration: InputDecoration(
      hintText: "Enter first number",
        border: InputBorder.none,
        fillColor: Color(0xfff3f3f4),
        filled: true)),

 

TextField(
    controller: fieldB,
    keyboardType: TextInputType.number,
    decoration: InputDecoration(
        hintText: "Enter second number",
        border: InputBorder.none,
        fillColor: Color(0xfff3f3f4),
        filled: true)),

 

Display the result

Text('Result = ${snapshot.data}',
  style: Theme.of(context).textTheme.headline2,
),

 

Create a button for operations

FlatButton(
    shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(18.0),
        side: BorderSide(color: Colors.red)
    ),
    onPressed: () => _bloc.calcEventSink.add(
        AddEvent(int.parse(fieldA.text),int.parse(fieldB.text))),
    child: Text("Addition")
),

 

Dispose bloc properly

@override
void dispose() {
  super.dispose();
  _bloc.dispose();
}

 

Flutter BLoC Output :

The implementation of Flutter BLoC pattern

If you have any query’s on this tutorial on flutter bloc pattern do let us know in comment section below.If you like this tutorial do like and share this tutorial for more interesting tutorials.

abhishek:
Related Post

This website uses cookies.