The BLoC Library
Learn to use the BLoC library to make your state management predictable, testable, and reliable.
Introduction to BLoC
BLoC stands for Business Logic Components. The main idea behind BLoC is that communication between components of the application is represented as a stream of events.
A Cubit is a lightweight implementation of the BLoC design pattern of state management. Cubit does not depend on events to emit new states; instead, it uses methods.
A Cubit contains the application’s state and emits it depending on the request made by methods from the UI.
In this tutorial, we’ll update the state of the app below using Cubit:
import 'package:flutter/material.dart'; import 'presentation/my_app.dart'; void main() { runApp(const MyApp()); }
Using Cubit
We first need to install the flutter_bloc
package. Locate # TODO-1: Install Cubit
in the pubspec.yaml
file (line 16) and install the package as shown:
dependencies:flutter:sdk: fluttercupertino_icons: ^1.0.2flutter_bloc: ^8.0.1
Import the package in respective files using import 'package:flutter_bloc/flutter_bloc.dart';
.
Creating the Cubit
and State
classes
Working with Cubit involves building our UI based on state. We need to define the different states of our app. In the lib/cubit/task_state.dart
file, add the different states shown below:
part of 'tasks_cubit.dart';@immutableabstract class TasksState{}class TasksInitial extends TasksState {List<Object> get props => [];}class TasksLoading extends TasksState {List<Object> get props => [];}class TasksLoaded extends TasksState {TasksLoaded(this.tasks);final List<Task> tasks;List<Object> get props => [tasks];}class TaskAdded extends TasksState {List<Object> get props => [];}class TaskCompleted extends TasksState {List<Object> get props => [];}class TaskDeleted extends TasksState {TaskDeleted(this.task);final Task task;Object get props => [task];}class ErrorState extends TasksState {List<Object> get props => [];}
We then create a Cubit that emits the states whenever a widget within our UI calls a method of the Cubit
class. ...