Book Image

Managing State in Flutter Pragmatically

By : RAHUL AGARWAL, Waleed Arshad
Book Image

Managing State in Flutter Pragmatically

By: RAHUL AGARWAL, Waleed Arshad

Overview of this book

Flutter is a cross-platform user interface (UI) toolkit that enables developers to create beautiful native applications for mobile, desktop, and the web with a single codebase. State management in Flutter is one of the most crucial and complex topics within Flutter, with a wide array of approaches available that can make it easy to get lost due to information overload. Managing State in Flutter Pragmatically is a definitive guide to starting out with Flutter and learning about state management, helping developers with some experience of state management to choose the most appropriate solutions and techniques to use. The book takes a hands-on approach and begins by covering the basics of Flutter state management before exploring how to build and manipulate a shopping cart app using popular approaches such as BLoC/Cubit, Provider, MobX, and Riverpod. Throughout the book, you'll also learn how to adopt approaches from React such as Redux and all its types. By the end of this Flutter book, you'll have gained a holistic view of all the state management approaches in Flutter, and learned which approach is the best solution for managing state in your app development journey.
Table of Contents (14 chapters)
1
Section 1:The Basics of State Management
4
Section 2:Types, Techniques, and Approaches
8
Section 3:Code-Level Implementation

Creating a shopping cart application with BLoC

We will be reusing the same screens we created in the previous chapter, with some editions specific to BLoC. Let's begin creating our shopping cart application using BLoC, as follows:

  1. Create a new Flutter application named cart_bloc.
  2. Copy the item.dart file from the previous chapter's code into the lib folder of your cart_bloc application. We will be reusing this file in all upcoming applications.
  3. Create a new file named cart_event.dart and add the following code to it:
    import 'item.dart';
    class CartEvent {}
    class AddItemToCartEvent extends CartEvent {
      final Item item;
      AddItemToCartEvent({required this.item});
    }
    class RemoveItemFromCartEvent extends CartEvent {
      final Item item;
      RemoveItemFromCartEvent({required this.item});
    }

    We created two events for our cart, one for adding an item to the cart and one for removing an item from the cart.

  4. Create a new...