Flutter Bloc Tutorial: Understand the Bloc Concepts

Published on August 14, 2024

Zignuts Technolab

flutter bloc
Flutter Development

Introduction

This blog explores Flutter Bloc, a well-known state management method that keeps business logic separate from the user interface. We'll look at how Bloc can streamline your development workflow and promote cleaner, more maintainable code.

State Management

State management is essential in Flutter app development to avoid having data spread out all over the place. By using state management, you can control data flow within your application and centralize the UI state.

What is Flutter Bloc?

Flutter Bloc is a state management solution for Flutter applications. The flutter_bloc library uses the Bloc (Business Logic Component) pattern to handle state management in Flutter.

flutter bloc tutorial

By separating the presentation layer from the business logic, Bloc promotes a clean and scalable architecture. Flutter Bloc is versatile, suitable for both simple educational projects and complex production applications.

It offers a structured approach to managing data and events within your app, resulting in a more organized and maintainable codebase.

Why Flutter Bloc?

When developing production-quality applications, effective state management is crucial.

As developers, we aim to:

  • Understand the current state of our application at any time.
  • Easily test every scenario to ensure the app responds correctly.
  • Log every user interaction to make data-driven decisions.
  • Work efficiently and reuse components within and across applications.
  • Enable many developers to work seamlessly within a single codebase using consistent patterns and conventions.
  • Create fast and responsive applications.

Bloc was designed to fulfill these requirements and more.

Flutter Bloc Concepts

There are several core concepts that are critical to understanding how to use the bloc package.

Bloc Widgets

  1. BlocBuilder : BlocBuilder is a Flutter widget that uses a Bloc and a builder function to build the widget based on new states, similar to StreamBuilder but with a simpler API to minimize boilerplate code.
  2. BlocSelector : BlocSelector is a Flutter widget similar to BlocBuilder, but it filters updates by selecting a new value based on the current bloc state, avoiding unnecessary builds if the selected value remains unchanged.
  3. BlocProvider : BlocProvider is a Flutter widget that supplies a Bloc to its children using BlocProvider.of<T>(context), enabling a single Bloc instance to be shared among multiple widgets within a subtree.
  4. MultiBlocProvider : MultiBlocProvider is a Flutter widget that combines multiple BlocProvider widgets into one, enhancing readability and eliminating the need for nested BlocProviders.
  5. BlocListener : BlocListener is a Flutter widget that takes a BlocWidgetListener and an optional Bloc, invoking the listener in response to state changes for one-time actions like navigation, showing a SnackBar, or displaying a Dialog.
  6. MultiBlocListener : MultiBlocListener is a Flutter widget that combines multiple BlocListener widgets into one, improving readability and eliminating the need for nested BlocListeners.
  7. BlocConsumer : BlocConsumer provides both a builder and a listener to handle new states, reducing boilerplate compared to using nested BlocListener and BlocBuilder.
  8. RepositoryProvider : RepositoryProvider is a Flutter widget that provides a repository to its children, serving as a dependency injection tool to share a single repository instance across multiple widgets within a subtree. 
  9. MultiRepositoryProvider : MultiRepositoryProvider is a Flutter widget that combines multiple RepositoryProvider widgets into one, enhancing readability and avoiding nested RepositoryProviders.

In the upcoming sections, we’re going to discuss BlocBuilder & MultiBlocProvider in detail as well as work through how they would apply to a Cart App.

The Cart App Example

Let's now build a basic Flutter application that utilizes Bloc to control and manage Product quantity and Cart State. This example will walk you through creating a BlocProvider, events, states, and setting up Bloc.

Integration Setup

Use this package as a library

Run this command with flutter in your project directory

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

Step By Step Flutter Bloc Project Organisation

Let's examine the project's general structure before getting into the code:

lib/bloc/ : Contains BLoC-related files.

  • cart_bloc.dart: The BLoC implementation for the cart.
  • cart_events.dart: Defines the events related to the cart.
  • cart_state.dart: Defines the state of the cart.

lib/models/ : Contains data models.

  • products.dart: Defines the product model.

lib/screens/ : Contains the UI screens.

  • cart_screen.dart: The screen displaying the cart.
  • products_screen.dart: The screen displaying the list of products.

1. Create the Bloc

Make a new Dart file for the Bloc in your project. Reactive state management is offered via the Bloc class from the flutter_bloc package, which is extended by the CartBloc class. The two primary actions that this class manages are adding and removing products from the basket.

cart_bloc.dart

The CartBloc class efficiently manages the state of a shopping cart by handling events that add or remove products. By using the BLoC pattern, the business logic for managing the cart is cleanly separated from the UI code, resulting in a more maintainable and testable application.

2.Event Class

Understanding Cart Events in Flutter's BLoC Pattern

In the context of the BLoC (Business Logic Component) pattern, events are the inputs that trigger state changes. They represent user actions or occurrences in the application. In this post, we'll explore the CartEvents class and its subclasses, AddProductEvent and RemoveProductEvent, which are crucial for managing the state of a shopping cart.

The CartEvents Class

CartEvents is an abstract class that serves as a base for all cart-related events. It doesn't contain any implementation itself but provides a common type for all specific cart events.

  • AddProductEvent is a subclass of CartEvents. It represents the action of adding a product to the cart. This event carries the name of the product to be added.
  • RemoveProductEvent is another subclass of CartEvents. It represents the action of removing a product from the cart. This event also carries the name of the product to be removed.

3.State Class

In this post, we'll explore the CartState class, which holds the state of a shopping cart. This class allows us to manage the products in the cart, including adding and removing items and retrieving item counts.

The CartState Class

The CartState class maintains the state of the cart using a map, where the keys are product names and the values are their quantities.

  • Managing Cart State:
    • The CartState class provides methods to modify the state of the cart by adding and removing products. These methods update the cart map accordingly.
    • When adding a product, cart.update is used to either increment the quantity if the product exists or set it to one if it doesn't.
    • When removing a product, cart.update is used to decrement the quantity if the product exists. If the quantity becomes zero, the product is removed from the map.
  • Creating New States:
    • The CartState.from constructor allows for the creation of new state instances based on existing states. This is particularly useful in a BLoC context, where state transitions are common.

4. Create the UI

4.1 The main.dart File

The main.dart file is the starting point of the Flutter application. It sets up the CartBloc and provides global access to it using the BlocProvider. Additionally, it defines routes for navigating between different screens in the app.

Here's a detailed breakdown of the main.dart file:

  • The BlocProvider at the root of the widget tree ensures that the CartBloc is available to all child widgets. 
  • This allows different parts of the app to access and interact with the cart state without needing to pass the BLoC instance through constructors.

4.2 The CartScreen Class

The CartScreen class is a Flutter widget that represents the shopping cart screen. It displays a list of products in the cart, along with their quantities. The state of the cart is managed using the BLoC pattern.

Here's a detailed breakdown of the CartScreen class:

State Management:

  • The CartScreen listens for changes in the CartState using the BlocBuilder widget.
  • When the state of the cart changes (e.g., products are added or removed), the BlocBuilder rebuilds the list to reflect the current state.

Displaying Cart Items:

  • The ListView.builder iterates over the products in the cart, creating a Row for each product.
  • The product name and quantity are displayed in the Row, with some padding for better visual spacing.

4.3 Product Screen Class

The ProductsScreen class integrates with the CartBloc and CartState to display a list of products, allowing users to add or remove items from their shopping cart.

The ProductsScreen Class

The ProductsScreen class is a Flutter widget that represents the product list screen. It displays a list of available products, with options to add or remove items from the cart. The state of the cart is managed using the BLoC pattern.

Here's a detailed breakdown of the ProductsScreen class:

State Management:

  • The ProductsScreen listens for changes in the CartState using the BlocBuilder widget.
  • When the state of the cart changes (e.g., products are added or removed), the BlocBuilder rebuilds the list to reflect the current state.

Displaying Products and Cart Items:

  • The ListView.builder iterates over the list of available products, creating a Row for each product.
  • The product name, quantity, and action buttons (add/remove) are displayed in the Row, with some padding for better visual spacing

Conclusion:

Flutter Bloc provides a robust and efficient solution for state management in Flutter applications, allowing developers to separate business logic from UI, leading to cleaner, more maintainable code. Through the Bloc pattern, complex state management tasks become streamlined, making it easier to manage application state, test scenarios, and scale projects. The example of the Cart App demonstrates how Bloc can be effectively used to handle events and state changes, enhancing the overall development workflow. By understanding and applying the core Bloc concepts, developers can create responsive and scalable applications with ease, ultimately improving the end-user experience.

To fully leverage the power of Flutter Bloc in your projects, consider working with our expert team at Zignuts. We specialize in Flutter development and can help you build scalable, efficient applications tailored to your needs. Whether you're starting a new project or optimizing an existing one, our skilled developers are ready to assist. Hire Flutter Developers from Zignuts and take your app development to the next level.

right-arrow
linkedin-blog-share-iconfacebook-blog-share-icontwitter-blog-icon
The name is required .
Please enter valid email .
Valid number
The company name or website is required .
Submit
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
download ready
Thank you for reaching out!
We’ve received your message and will get back to you as soon as possible.
contact us

Portfolio

Recent

explore-projects

Testimonials

Why they’re fond of us?

tm img

A reliable and flexible technical partner, Zignuts Technolab enables a scalable development process. The team offers a comprehensive array of expertise and scalability that yields an optimized ROI. Direct contact with specialists maintains a seamless workflow and clear communication.

Joeri

Technical Architect
Blockchain-based Real Estate Platform Company, Belgium

Zignuts Technolab transformed our platform by simplifying code, redesigning key aspects, and adding new features, all within impressive timelines. Their project management and communication were exceptional.

Ali

Managing Director
Automobile Company, UAE

Zignuts team has been instrumental in our platform’s development including backend, frontend and mobile apps, delivering excellent functionality and improving speed over time. Their project management, pricing and communication are top-notch.

Shoomon

Co-Founder
AI-Based Fintech Startup, UK

Zignuts has delivered excellent quality in developing our website and mobile apps. Their genuine interest in our business and proactive approach have been impressive.

Jacob

Technical Architect
Blockchain-based Real Estate Platform Company, Belgium

Their team's dedication and knowledge in handling our relocation information platform made the collaboration seamless and productive. Highly recommend their services.

Stephen

CEO & Founder
Social Community Platform, Germany

Zignuts Technolab provided highly skilled full-stack developers who efficiently handled complex tasks, from backend development to payment gateway integration. Their responsiveness and quality of work were outstanding.

Houssam

Chief Product Officer
Enterprise Solutions, Jordan

Zignuts Technolab has been highly efficient and responsive in developing our rewards and wellness app. Their ability to integrate feedback quickly and their solid expertise make them a great partner.

Namor

Developer
Wellness Startup, Thailand