Table of contents
Today, I delved into the world of state management in Flutter, focusing on Cubit and Bloc. Here's a summary of what I learned:
State refers to the data that changes over the lifecycle of an application. There are two types of state:
Local State: This refers to data contained within widgets. To manage local state, we typically use
setState()
in StatefulWidgets or wrap the widget withStatefulBuilder
in StatelessWidget.Global State: when state needs to be shared between multiple widgets (e.g., child to parent, sibling to sibling), managing it can become challenging. This is where state management tools like Provider, Cubit, and Bloc come in handy.
Cubit:
Cubit, a lightweight and intuitive state management solution provided by the Bloc library, simplifies the process of managing state. I applied my knowledge of Cubit by implementing a Counter demo application.
Here's the code on how we can use Cubit.
import 'package:flutter_bloc/flutter_bloc.dart'; //we create a Cubit that extends Cubit class CounterCubit extends Cubit<int> { //Cubit<dynamic> requires a initialState value within a Constructor. CounterCubit() : super(0); int get count => state; void increment() => emit(state + 1); //emit method will cause the widget to rebuild }
then we can access the State value from widgets using many methods:
BlocBuilder widget.
Here Wrap widget that requires the data with BlocBuilder and provide a method for the builder.
//access the State value from widgets BlocBuilder<CounterCubit, int>( builder: (context, count) { return Text('$count'); }, )
BlocProvider:
Wrap the root widget with the BlocProvider and use the following,
import 'package:flutter_bloc/flutter_bloc.dart';// without rebuilding final counter = context.read<CounterCubit>().state; // automatically rebuild on state changes final counter = context.watch<CounterCubit>().state;
Today's exploration into state management with Cubit and Bloc has been insightful. I've learned how to effectively manage state in Flutter applications, both locally and across multiple widgets. I look forward to applying these techniques in future projects.