In this article, we will cover on BLoC pattern in flutter, which is also known as Business logic component, I highly recommend design pattern in coding because its a standard way and with applying design patterns you can easily change your code in future which is very panic if you are working in big project so design pattern will help you to get rid of changing code in future tension, as design pattern is standard way so other developer can also understand your code, there are a lot of advantages of design pattern so I highly recommend you to code according to design patterns, after working on BLoC pattern in flutter give me outstanding experience and now my favorite design pattern is BLoC because its very easy and effective to solve your complex problems. So lets start understanding the BLoC pattern in flutter from basics and in easy way.


BLoC pattern in flutter
BLoC pattern in flutter


BLoC consists of 4 elements and it is very important to understand these 4 elements before BLoC because these 4 element is used in BLoC pattern.

1. States :

State is the data which app currently showing to user, for example login screen is login state and when you login to your account new state appears that is dashboard state (dashboard screen)

2. Events

Any action that is detect by application like button click is known as event.

3. Stream

Stream is medium through which your data transfer from User interface to backend then in response it callback from backend to User Interface.

4. Sink

Sink is point where your streamed data is consumed or received.



BLoC Pattern in flutter 

BLoC pattern has 3 different components that is UI (user interface), BLOC and data provider. lets explain these components further in details.


User Interface ( View )

It is dummy design or view totally depended on BLOC component and this is front end design, all streamed data had sinked this component. In simple words UI component consist of different states and BLOC has the control to change its state.


BLOC

It contains business logic and also update or change the state of UI of your app. BLOC is main component in this design pattern because both data provider and UI is dependent on it, all logic stuff is to be dealt here.

Data Provider

Data provide is raw data that is used by BLOC component that can be any database or string file path and anything that is known as data.


Advantages of BLoC pattern in flutter

1. BLoC is easiest pattern to understand and applied in your project because it has only 3 components.

2. BLoC separate the view code from logic code which reduce complexity and enhance code readability

3. BLoC pattern is standard way to code for your project so other developer can easily understand.

4. BLoC pattern helps you to increase project flexibility so any developer can easily change code without effecting whole project or modules.

5. BLoC provide you way to solve problem effectively in simple way.


BLoC flutter examples

I will take a simple example of BLoC pattern that is simple counter app in flutter, this counter app has two buttons that is increment and decrement which increase or decrease the current counter and text  widget will show current number in counter app as result. First of all let's add code of business logic in separate file named it as Counter logic
enum CounterEvent { increment, decrement }
class CounterLogic extends Bloc<CounterEvent, int> { int get initialState => 0; Stream<int> mapEventToState(CounterEvent event) async* { switch (event) { case CounterEvent.decrement: yield state - 1; break; case CounterEvent.increment: yield state + 1; break; } } }

Flutter have already build-in code for BLoC so you don't worry to write code from scratch. Just understand few basics things and that is create class and extend it with Bloc keywords it will accepts two parameters one is enum of different events for my case I have only two events mentioned above in code, second parameter is your data type that can be int, double and string etc. Now you have to override one method called mapEventToState and one property called initial Stage as all details are available above in code. Now let's create main class.


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

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Counter App',
      home: BlocProvider<CounterLogic>(
        create: (context) => CounterLogic(),
        child: CounterPage(),
      ),
    );
  }
}

The method main with void return type has all control and it will run first. In the main method I am running the MyApp class which is stateless widget. According to syntax add reference of BLoC provider to home of widget so Counter Logic will be applied to whole screen, now let's talk about Counter Page, it contain two button and one text widget. In flutter everything is widgets.


class CounterPage extends StatelessWidget {
  
  Widget build(BuildContext context) {
    final CounterLogic counterBloc = BlocProvider.of<CounterLogic>(context);

    return Scaffold(
      appBar: AppBar(title: Text('Counter')),
      body: BlocBuilder<CounterLogic, int>(
        builder: (context, count) {
          return Center(
            child: Text(
              '$count',
              style: TextStyle(fontSize: 24.0),
            ),
          );
        },
      ),
      floatingActionButton: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(vertical: 5.0),
            child: FloatingActionButton(
              child: Icon(Icons.add),
              onPressed: () {
                counterBloc.add(CounterEvent.increment);
              },
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 5.0),
            child: FloatingActionButton(
              child: Icon(Icons.remove),
              onPressed: () {
                counterBloc.add(CounterEvent.decrement);
              },
            ),
          ),
        ],
      ),
    );
  }
}


Previous Post Next Post