Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Bloc V/S Cubit In Flutter Application

Hello Everyone!!! Today we learn about Bloc V/S Cubit In Flutter Application. In this article, we cover topics like what is bloc. , what is a cubit and what’s the difference between a bloc and a cubit?

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents

What is Bloc?

What is Cubit?

Bloc VS Cubit

Add Dependency

Implementation

Conclusion

GitHub Link


What is Bloc?

Flutter Bloc is one of the state management in a flutter. We can use it to handle all the states that we want to perform in our Flutter applications.

Bloc is the best and simple way to do state management. We can easily add any type of change to the Flutter application. You can easily learn the concept, no matter what’s your level. You can add this dependency to your project and use it.

Bloc is a design pattern created by Google to help separate business logic from the award layer and authorize a developer to exploit code more efficiently.

A state management library called Bloc was created and maintained by Felix Angelo. It assists developers utensil the Bloc design pattern in their Flutter application. It means that a developer must recognize the state of an app at some time. There should be something on the screen for every interplay with the app to let users know what the incident is incident.

what is a Cubit?

Cubit is a minimal version or a subset of the BLoC design pattern that simplifies the way we manage the state of an application. To do so, it substitutes the use of events (used in Bloc) with functions that rebuild the UI by emitting different states on a stream.

A Cubit is similar to a Bloc but has no notion of events and relies on methods to emit new states. Every Cubit requires an initial state which will be the state of the Cubit before emit has been called. The current state of a Cubit can be accessed via the state-getter.


Bloc VS Cubit:

The only difference is in the syntax of the emitting state. Where Cubit uses emit(event) syntax, State Notifier uses state = event. Bloc on the other hand relies on events instead of functions to get feedback from UI to Cubit. The major difference between Bloc and Cubit is, “Bloc is Event-Driven and Cubit is not Event-Driven”. In Bloc, we can override “onTransition” and check how these events are coming and how these states change. In Cubit, we call functions to send these states, with the help of these functions we can track the state. We use the “onChnaged” function in Cubit.


Add Dependency:

Open the terminal in your Flutter project. Then run the following command to install the flutter_bloc package in your Flutter Project.

$ flutter pub add flutter_bloc

or you will add this line to your package’s pubspec. ymal file and run “flutter pub get”

dependencies:
flutter_bloc: ^8.1.2

Import it. Now in your Dart code, you can use:

import 'package:flutter_bloc/flutter_bloc.dart';

Implementation

First, we have to add dependency in pubspec.ymal file for getting all the properties of the bloc by which we can easily use it for state management.

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_bloc: ^8.1.2

For this demo first, we have to create a logic folder in which we create classes for cubit_logic and bloc_logic. So starts with bloc_logic. For bloc_logic we have to create two classes for counter_bloc and counter_event.

Counter_event.dart:

abstract class CounterEvent{}

class CounterIncrementEvent extends CounterEvent{}

In this, we create a Counter-event which is used in counter_bloc, and also define the CounterIncrementEvent.

counter_bloc.dart:-

class CounterBloc extends Bloc<CounterEvent, CounterState>{
CounterBloc() : super(CounterInitState());

Stream<CounterState> mapEventToState(CounterEvent event) async*{
switch (event.runtimeType){
case CounterIncrementEvent:
int value = state.value;
value++;
yield CounterResultState(value);
break;
default:
}
}
}

First, we extend the class with Bloc in which we pass the event and state of the bloc. And create a stream with a state in which we pass the event that we want to perform in the application. For the event, we use a switch case.

home.dart:-

In the UI part, first, we have to define counterBloc.

CounterBloc counterBloc;

and pass this counterBloc in initState(). And create a method in which we increment the number.

void _incrementCounter(){
counterBloc.add(CounterIncrementEvent()); ///bloc_state
}

After that, we create a widget that is wrapped with BlocProvider and pass CounterBloc. and give counterBloc as created in BlocProvider. For that the UI we used BlocBuilder by which we can change the text of the UI. At the onPreesed of the button, we pass the method that we created for increment.

Widget blocStateScreen(BuildContext context) {
return BlocProvider<CounterBloc>(
create: (context)=> counterBloc,
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(AppStrings.appbarText),
),
body: Center(
child: Padding(
padding: const EdgeInsets.only(top: 200),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(AppStrings.blocCounter),
BlocBuilder<CounterBloc, CounterState>(
builder: (context, state)
=> Text('${state.value}')),
OutlinedButton(
style: ButtonStyle(
side: MaterialStateProperty.all(const BorderSide(
color: Colors.black,
width: 1.5,))),
onPressed: () {
_incrementCounter();
},
child: const Text('+', style: TextStyle(fontSize: 25),))
],
),
),
),
),
);
}

Output of Bloc


counter_state:-

In counter_state.dart we create an abstract class with the name CounterState in which we initialize the value. And also create two more classes for InitState and ResultState.

abstract class CounterState {
late final int value;
@override
CounterState(this.value);
}

class CounterInitState extends CounterState{
CounterInitState(int value) : super(0);
}

class CounterResultState extends CounterState{
CounterResultState(int value) : super(value);
}

counter_cubit.dart:-

In counter. dart class, we create a cubit class that extends to CubitState, in this class, we define the method of incrementing the number. and emit the value of ResultState.

class CounterCubit extends Cubit<CounterState>{
CounterCubit() : super(CounterInitState(0));

void increment() async{
int value = state.value;
value++;

emit(CounterResultState(value));
}
}

home.dart:-

In the UI part, first, we have to define counterBloc.

CounterCubit counterCubit;

and pass this counterBloc in initState(). And create a method in which we increment the number.

void _incrementCounter(){
counterCubit.increment();
}

After that, we create a widget that is wrapped with BlocProvider and pass CounterCubit. and give counterCubit as created in BlocProvider. For that the UI we used BlocBuilder by which we can change the text of the UI. At the onPreesed of the button, we pass the method which we created for increment.

Widget cubitStateScreen(BuildContext context) {
return BlocProvider<CounterCubit>(
create: (context)=> counterCubit,
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(AppStrings.appbarText),
),
body: Center(
child: Padding(
padding: const EdgeInsets.only(top: 200),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(AppStrings.cubitCounter),
BlocBuilder<CounterCubit, CounterState>(
builder: (context, state)
=> Text('${state.value}')),
OutlinedButton(
style: ButtonStyle(
side: MaterialStateProperty.all(const BorderSide(
color: Colors.black,
width: 1.5,))),
onPressed: () {
_incrementCounter();
},
child: const Text('+', style: TextStyle(fontSize: 25),))
],
),
),
),
),
);
}

Output of Cubit


Conclusion:

In this article, we have been through What is Bloc And Cubit in Flutter along with how to implement them in a Flutter. By using we can perform many state management orations.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


GitHub Link:

Find the source code of the Bloc VS Cubit In Flutter Application:

GitHub – flutter-devs/bloc-cubit_demo
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.