Explanation of bloc in flutter with example

Explanation of  bloc in flutter with example


Hi Everyone, welcome to another post Today we will learn Integration of Bloc library Today we are going to build one flutter app based on bloc library before deep drive we need to understand what is Bloc and why we need..


In Flutter, a Bloc is a design pattern that separates the business logic of an app from its user interface (UI). The Bloc pattern allows developers to build reusable and testable business logic that can be shared across multiple UI elements.



Here's an example of how you might use a Bloc in a Flutter app:


Step 1:- Create one new flutter project.


Step 2:- Create one enum of "CounterEvent" with two values increment and decrement.


enum CounterEvent { increment, decrement }


Step 3:- And create one class named as "CounterBloc" and extends the class  with "Bloc<CounterEvent, int>" and implements its method.


class CounterBloc extends Bloc<CounterEvent, int> {  

@override

  int get initialState => 0;


  @override

  Stream<int> mapEventToState(CounterEvent event) async* {

    //todo

  }

}



Step 4: Handle the core logics in CounterBloc class.


class CounterBloc extends Bloc<CounterEvent, int> {  

@override

  int get initialState => 0;


  @override

  Stream<int> mapEventToState(CounterEvent event) async* {

    switch (event) {

      case CounterEvent.increment:

        yield state + 1;

        break;

      case CounterEvent.decrement:

        yield state - 1;

        break;

    }

  }

}




Step 5: Now you are ready to connect CounterBloc with our UI widget.


import 'package:flutter/material.dart';

import 'package:flutter_bloc/flutter_bloc.dart';


void main() {

  runApp(

    BlocProvider(

      create: (context) => CounterBloc(),

      child: MyApp(),

    ),

  );

}


class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'Flutter Demo',

      home: MyHomePage(),

    );

  }

}


class MyHomePage extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    final CounterBloc counterBloc = BlocProvider.of<CounterBloc>(context);


    return Scaffold(

      appBar: AppBar(title: Text('Counter')),

      body: BlocBuilder<CounterBloc, 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(

              onPressed: () => counterBloc.add(CounterEvent.increment),

              child: Icon(Icons.add),

            ),

          ),

          Padding(

            padding: EdgeInsets.symmetric(vertical: 5.0),

            child: FloatingActionButton(

              onPressed: () => counterBloc.add(CounterEvent.decrement),

              child: Icon(Icons.remove),

            ),

          ),

        ],

      ),

    );

  }

}



Here is the complete implementation


import 'package:flutter/material.dart';

import 'package:flutter_bloc/flutter_bloc.dart';


void main() {

  runApp(

    BlocProvider(

      create: (context) => CounterBloc(),

      child: MyApp(),

    ),

  );

}


class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'Flutter Demo',

      home: MyHomePage(),

    );

  }

}


class MyHomePage extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    final CounterBloc counterBloc = BlocProvider.of<CounterBloc>(context);


    return Scaffold(

      appBar: AppBar(title: Text('Counter')),

      body: BlocBuilder<CounterBloc, 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(

              onPressed: () => counterBloc.add(CounterEvent.increment),

              child: Icon(Icons.add),

            ),

          ),

          Padding(

            padding: EdgeInsets.symmetric(vertical: 5.0),

            child: FloatingActionButton(

              onPressed: () => counterBloc.add(CounterEvent.decrement),

              child: Icon(Icons.remove),

            ),

          ),

        ],

      ),

    );

  }

}


enum CounterEvent { increment, decrement }


class CounterBloc extends Bloc<CounterEvent, int> {

  @override

  int get initialState => 0;


  @override

  Stream<int> mapEventToState(CounterEvent event) async* {

    switch (event) {

      case CounterEvent.increment:

        yield state + 1;

        break;

      case CounterEvent.decrement:

        yield state - 1;

        break;

    }

  }

}


In this example, the CounterBloc is a Bloc that manages the state of a simple counter. The CounterBloc has an initialState of 0, and it defines two events: increment and decrement. The mapEventToState method is called whenever an event is dispatched, and it returns a new state based on the event that was dispatched.


The MyHomePage widget displays the current count in a Text widget and has two FloatingActionButtons that allow the user to increment or decrement the count. When one of these buttons is pressed, it calls the corresponding method on the CounterCubit, which updates the state and triggers a rebuild of the UI.


In short, the Bloc pattern is a design pattern that separates the business logic of an app from its user interface (UI)


It allows developers to build reusable and testable business logic that can be shared across multiple UI elements. In a Flutter app, a Bloc is implemented as a class that extends the Bloc class from the flutter_bloc package


The Bloc class takes two generic type arguments: the Event type and the State type. The Bloc has an initialState and a mapEventToState method, and it defines a Stream of state changes that can be consumed by the UI. 


The UI can dispatch events to the Bloc by calling the add method, and it can rebuild itself based on the current state of the Bloc by using a BlocBuilder widget.



I hope this help!!


Post a Comment

0 Comments