Flutter for Jobseekers

State Management and the BLoC

Ephemeral versus app state, and one shopping cart built four ways — with an inherited widget, Provider, Cubit and BLoC.

State Management and the BLoC

Every application has some sort of state. Whether that is the state in one of your stateful widgets or whether the user is logged in, there is state everywhere. Understanding what state is and how to manage it is essential for any application.

In this chapter, we are going to explore several approaches to state management in Flutter applications. We will look at just a couple of the more popular approaches, and even build an app with them so we can compare their differences.

Companion code: the publisher's repository holds this chapter's code as Example 9.1–Example 9.35 in the Chapter 09 folder; most examples are the whole program up to that point, so each code block below is labelled with the first example that contains it. Blocks without a label have no counterpart in the repository. The repository's constructors use the older {Key? key}) : super(key: key) form instead of {super.key}, and it has conversion glitches of its own, so the code on this page follows the book (BPB Publications, n.d.).

Chapter overview

Structure

  • Ephemeral versus app state
  • Some prep work before we begin
  • A brief aside to explain some new concepts
  • Using inherited widgets to manage app state
  • Using Provider to manage app state
  • Using BLoC's Cubit to manage app state
  • Using BLoC to manage app state

Objectives

After completing this chapter, you will have a firm understanding of the difference between the state of a widget and the state of an entire application. You will learn how to use Flutter's built-in widgets to manage app state before exploring several popular packages, which make working with app state much easier. Finally, you will build a simple application to use as a tool to compare the different approaches to state management.

Runnable example

The shopping cart built with an inherited widget, Provider, Cubit and BLoC is also available as a runnable project with tests in examples/flutter_for_jobseekers_ch09/. The code on this page is shown as the book prints it, with conversion glitches fixed.

Ephemeral versus app state

When we are talking about state, there are two different kinds of state: ephemeral and app state.

Ephemeral state

You are already familiar with the first, although you may not know it by name. This is the sort of state that is used to hold the necessary information to build widgets. Things like the current index of a BottomNavigationBar, the connection state of an API call, and whether a checkbox is checked are all examples of ephemeral state. These are states managed by a stateful widget.

Remember, though, that widgets are immutable. Once a widget is built, it cannot be changed. Instead, it is tossed away and rebuilt when its associated State object is updated. When the widget is disposed of, so too do we lose any associated State object. This is what we mean by ephemeral state.

App state

App state, on the other hand, is state that is consumed throughout the application. If you have an app that allows a user to log in, the app state will hold the login state. If the user logs out, the login state would be updated and widgets throughout the application will be rebuilt (or disposed of) as necessary. The bulk of the widgets may get disposed of, and the user would be routed to the login screen, perhaps.
While you could create a stateful widget at the top of your widget tree that holds the state, you would need to pass that state down to every child widget, which needs to access it (or one of its children does). This is, generally, a horrible idea. Do not do this.

Well, what about inherited widgets, then? Is not the idea behind an inherited widget that you can access through the BuildContext from anywhere below it in the widget tree? Yep! That is right — and it is inherited widgets which we will use to manage the app state, if not directly, by utilizing packages that are wrappers around inherited widgets.

If you need a refresher on inherited widgets, now would be an excellent time to go back and review them in Chapter 4: Introduction to Widgets. Once you have brushed up on inherited widgets, let us look at how to use them to manage app state.

Some prep work before we begin

We are going to be building a very simple shopping cart in the examples in this chapter. This is not a fully featured shopping cart, but it will be enough to help us illustrate the concepts.

Inventory

A list of items that are for sale and an add item to cart button.

Shopping cart

Contains the items we have added to the cart. Each item in the cart will have a multiplier next to it, so if you add several of a single item, the multiplier will increase.

Totals

A count of all the items in the cart, alongside the total cost of everything in the cart, plus a clear cart button.

Let us start by defining what an Item is. It should, at a minimum, have a cost and a name. You could spend more time adding a product image or other properties, but that is outside the scope of this chapter:

Example 9.1 · Example 9.1.dart
class Item {
  final double cost;
  final String name;

  const Item({
    required this.cost,
    required this.name,
  });
}

Now that we have defined what an Item is in our store, we can use this class to build up an inventory:

Example 9.2 · Example 9.2.dart
const List<Item> inventory = [
  Item(name: "Shirt", cost: 12.99),
  Item(name: "Shoes", cost: 120.00),
  Item(name: "Pants", cost: 63.74),
  Item(name: "Hat", cost: 8.23),
];

Runnable copy: examples/flutter_for_jobseekers_ch09/lib/item.dart (shared by all four apps). The book's text lost the integer part of the prices in conversion; they are restored from the publisher's companion repository, Example 9.2 (BPB Publications, n.d.).

For our main app, we are just going to create a ListView that has the inventory on top and the shopping cart on the bottom. We will make it a stateful widget, which we will come back to later:

Example 9.3 · Example 9.3.dart
class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: [
              Inventory(),
              ShoppingCart(),
            ],
          ),
        ),
      ),
    );
  }
}

Let us first look at the shopping cart. Both the shopping cart and inventory widgets will have a couple of nested ListViews, which we will need to be careful not to have scroll independently since we are wrapping the whole UI in its own ListView that will handle scrolling.

For this reason, we apply the ClampingScrollPhysics class to the ListViews to prevent them from scrolling. The net result is akin to using a Column, but with the performance benefits of using the ListView.

Here is the shopping cart:

Example 9.4 · Example 9.4.dart
class ShoppingCart extends StatelessWidget {
  const ShoppingCart({super.key});

  @override
  Widget build(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      physics: const ClampingScrollPhysics(),
      children: [
        Text(
          'Shopping Cart',
          style: Theme.of(context).textTheme.displayMedium,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            // TODO: Display the total number of items in the cart
            Text('Items in Cart: '),
            // TODO: Display the total cost of all items in the cart
            Text('Total Cost: '),
            OutlinedButton.icon(
              label: const Text('Clear cart'),
              icon: const Icon(Icons.remove_shopping_cart),
              onPressed: () {
                // TODO: Add a "clear cart" handler
              },
            ),
          ],
        ),
        ListView.builder(
          shrinkWrap: true,
          physics: const ClampingScrollPhysics(),
          // TODO: Figure out how many unique items are in our cart
          itemCount: 0,
          itemBuilder: (context, i) => Card(
            child: ListTile(
              // TODO: Figure out how many of a specific item are in our cart
              leading: Text(''),
              // TODO: Display the item's name
              title: Text(''),
              // TODO: Display the item's price
              subtitle: Text(''),
            ),
          ),
        ),
      ],
    );
  }
}

And here is the inventory:

Example 9.5 · Example 9.5.dart
class Inventory extends StatelessWidget {
  const Inventory({super.key});

  @override
  Widget build(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      physics: const ClampingScrollPhysics(),
      children: [
        Text(
          'Inventory',
          style: Theme.of(context).textTheme.displayMedium,
        ),
        ListView.builder(
          shrinkWrap: true,
          physics: const ClampingScrollPhysics(),
          itemCount: inventory.length,
          itemBuilder: (BuildContext context, int i) => Card(
            child: ListTile(
              title: Text(inventory[i].name),
              subtitle: Text('\$${inventory[i].cost.toStringAsFixed(2)}'),
              trailing: IconButton(
                icon: const Icon(Icons.add_shopping_cart),
                onPressed: () {
                  // TODO: Add the item to the shopping cart.
                },
              ),
            ),
          ),
        ),
      ],
    );
  }
}

Before we move on to fixing all the TODOs in our code, let us look at a couple of new concepts that were just introduced.

A brief aside to explain some new concepts

The two things here that may be new or unfamiliar are the => operator and the \${inventory…} in the Text widget. Let us quickly go over these so you know what they mean and how to use them.

The => operator

The => operator is shorthand for return this thing. Take the following method, which returns a string:

Example 9.6 · Example 9.6.dart
String sayHello() {
  return "Hello";
}

Since this method only returns a value and does not have any complex logic, we can simplify it using the => operator, like the following:

Example 9.6 · Example 9.6.dart
String sayHello() => "Hello";
And that is the gist of it. If your method needs to do some processing before returning the value, you will want to use the return style, otherwise you should be able to save a few keystrokes with the => operator.

Escaping and interpolation

Now, let us investigate the \${inventory…} in our Text widget. There are two things happening here that we need to discuss: escaping and interpolation. Let us talk about escaping, first.

Escaping

There are some characters that, when inserted into a string, are treated as special characters. These include, but are not limited to, the backslash (\), single and double quotes (' and ") and the dollar sign ($). However, there are caveats and conditions as to when these are treated as special characters.

For example, the string "it's a wonderful life" has no problems whatsoever, even though there is a single quote in the middle of it. However, if we try to use single quotes around our string, such as with 'it's a wonderful life', we will run into a problem. Can you see it? The problem is that we contain our string within quotes — in this case, single quotes — but we have inserted a single quote in the middle. Effectively, we have told Dart that our string is simply 'it', and everything that comes after is going to cause Dart to complain.

To get around this, we can use the backslash to escape the single quote, thereby telling Dart that we really do want a single quote in our string, like the following: 'it\'s a wonderful life'. That is escaping, in a nutshell.

Interpolation

Interpolation is denoted by the following inside a string: ${}. Anything you put between the braces will be executed by Dart and the output will be inserted into the string as plain text. In our example, we are getting the price of an item, then running the method .toStringAsFixed(2) on it, which will ensure the cost always has two digits after the decimal, regardless of how the cost was originally set.

If you simply wanted the value of a variable to be inserted into your string, you could prefix the variable with a dollar sign: "I would like to say $hello." is an example of this in action. If your hello variable is a class with properties, you would need to use interpolation: "I would like to say ${hello.toYou}".

Now, let us see why we have an escaped dollar sign. Since the dollar sign is used to denote that the characters which follow are to be treated as a variable and/or an interpolated string, inserting that dollar sign into our string to display a cost in dollars requires us to escape the dollar sign: '\$100' because 100 is not a variable, but a string of text.

The final question remains: why do we need to interpolate in the first place? The answer is: because we are using the => operator, we cannot assign a variable for the price string and simply use $price in our string.

Using inherited widgets to manage app state

In Chapter 4: Introduction to Widgets, we learned about inherited widgets and that they can hold a value that we can then find anywhere below in the widget tree by referencing the current context. If we create an inherited widget with a list of items in the cart, we can reference that list anywhere by accessing the inherited widget using BuildContext. The trick is updating that list as we add items to and clear our cart. Otherwise, we are not breaking new ground here. In fact, the core of our inherited widget should look very familiar:

Example 9.7 · Example 9.7.dart
class ShoppingCartInheritedWidget extends InheritedWidget {
  final List<Item> itemsInCart;
  @override
  const ShoppingCartInheritedWidget({
    super.key,
    required super.child,
    required this.itemsInCart,
  });

  @override
  bool updateShouldNotify(ShoppingCartInheritedWidget oldWidget) {
    return oldWidget.itemsInCart != itemsInCart;
  }

  static ShoppingCartInheritedWidget? of(BuildContext context) {
    return context
        .dependOnInheritedWidgetOfExactType<ShoppingCartInheritedWidget>();
  }
}

We pass in a list of items, and then we can access that list from anywhere. We are not quite done with our inherited widget, though. Right now, we can change our cart, but unless we specifically ask for those changes, we will never know that those changes happened. What we want to happen is: (1) we update the cart and (2) our ShoppingCart updates automatically. For this, we need to use a ValueChanged.

ValueChanged and typedef

ValueChanged is not so much a widget, but a typedef.

We can specify our own types without creating a new class by using typedef. For example, we could say typedef StringList = List<String>; then use StringList in place of List<String>.

In fact, ValueChanged is defined as follows: typedef ValueChanged<T> = void Function(T value). So, it is a function that takes in a value.

Let us quickly get that set up in our inherited widget. First, we need to add it as a property:

Example 9.8 · Example 9.8.dart
class ShoppingCartInheritedWidget extends InheritedWidget {
  final List<Item> itemsInCart;
  final ValueChanged<List<Item>> onListChanged;
  @override
  const ShoppingCartInheritedWidget({
    super.key,
    required super.child,
    required this.itemsInCart,
    required this.onListChanged,
  });

Then we want to update the method to use it:

Example 9.8 · Example 9.8.dart
@override
bool updateShouldNotify(ShoppingCartInheritedWidget oldWidget) {
  return oldWidget.itemsInCart != itemsInCart ||
      oldWidget.onListChanged != onListChanged;
}

Holding the cart in _MyAppState

That is all we need to do in our inherited widget, but we still need to create the method and pass it in. We will do that in the _MyAppState, which brings us back to why we are using a stateful widget and not a stateless widget.

Although we are using the inherited widget to access the state of our list anywhere in the application, it is the MyApp widget that truly holds the app state. This is where we will define a private variable to hold the items in our cart:

Example 9.9 · Example 9.9.dart
class _MyAppState extends State<MyApp> {
  List<Item> _itemsInCart = [];

  @override
  Widget build(BuildContext context) {

And it is that variable that we will pass into our inherited widget. We also need to write our method to pass in. Let us do that now that we have our list set up:

Example 9.10 · Example 9.10.dart
class _MyAppState extends State<MyApp> {
  List<Item> _itemsInCart = [];

  @override
  Widget build(BuildContext context) {
    ...
  }

  void onCartUpdated(List<Item> items) => setState(() {
        _itemsInCart = items;
      });
}

This method could not be any simpler: when a list of items is passed into the method, update the _itemsInCart variable to match. Next, we need to wrap our ListView with the inherited widget we have created and pass both the _itemsInCart variable as well as our onCartUpdated method into it:

Example 9.11 · Example 9.11.dart
@override
Widget build(BuildContext context) {
  return MaterialApp(
    home: Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: ShoppingCartInheritedWidget(
          itemsInCart: _itemsInCart,
          onListChanged: (List<Item> items) => onCartUpdated,
          child: ListView(
            children: [
              Inventory(),
              ShoppingCart(),
            ],
          ),
        ),
      ),
    ),
  );
}
Corrected:(List<Item> items) => onCartUpdated does not call onCartUpdated. The closure's body only refers to the method (a tear-off) and returns it, so invoking onListChanged(items) runs onCartUpdated zero times. Pass the method itself: onListChanged: onCartUpdated, as the runnable copy does. (In the book's app nothing calls onListChanged anyway: the widgets call the onCartUpdated passed to them below.)

There is still something missing, though. How do we call the onCartUpdated method when we add an item to our cart or clear our cart? We are going to have to pass the method into our Inventory and ShoppingCart widgets and call them there:

Example 9.12 · Example 9.12.dart
child: ListView(
  children: [
    Inventory(onCartUpdated),
    ShoppingCart(onCartUpdated),
  ],
),

You will also need to update each of the widgets to allow us to pass in a positional parameter. Here is the ShoppingCart as an example:

Example 9.13 · Example 9.13.dart
class ShoppingCart extends StatelessWidget {
  final Function(List<Item>) onCartUpdated;

  const ShoppingCart(this.onCartUpdated, {super.key});
  ...
}

Updating the Inventory

Believe it or not, we are nearly finished. Let us focus next on the Inventory before moving on to the ShoppingCart. First, we need to figure out what is already in the cart so we can add more things to it. That is easy enough since we now have an inherited widget:

Example 9.14 · Example 9.14.dart
@override
Widget build(BuildContext context) {
  final List<Item> currentCart =
      ShoppingCartInheritedWidget.of(context)!.itemsInCart;
  ...
}

Now all that is left is to update the onPressed method of our add to cart button. This method needs to do two things:

Add the item

Take the current cart and add an item to it, and

Notify

Invoke the onCartUpdated method with our new cart.

Example 9.15 · Example 9.15.dart
onPressed: () {
  currentCart.add(inventory[i]);
  onCartUpdated(currentCart);
},

Note how we assigned the currentCart variable inside the build method. This will clear the list and rebuild the widget each time the cart changes, so the currentCart will always match what is in the inherited widget's cart. We could also use this logic to conditionally display an out of stock message on items in the inventory that have less in stock than the number of items in the cart (minus one).

Corrected:currentCart.add(...) changes the list held by _MyAppState in place, and onCartUpdated then assigns that same list back to _itemsInCart. So oldWidget.itemsInCart != itemsInCart in updateShouldNotify compares a list with itself and is always false. The cart still updates because setState rebuilds MyApp, which creates new Inventory and ShoppingCart widgets; the runnable copy's tests confirm this.

Updating the ShoppingCart

At this point, the Inventory widget is complete. Pressing the add to cart button will update the cart in our inherited widget. The ShoppingCart is not being updated, however, so let us fix that now.

Just like with the Inventory, we are going to get the cart from the inherited widget. Once we have the cart, we can check off a couple of TODOs:

Example 9.16 · Example 9.16.dart
Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: [
    Text('Items in Cart: ${currentCart.itemsInCart.length}'),
    // TODO: Display the total cost of all items in the cart
    Text('Total Cost: '),
    OutlinedButton.icon(
      label: const Text('Clear cart'),
      icon: const Icon(Icons.remove_shopping_cart),
      onPressed: () => onCartUpdated([]),
    ),
  ],
),
Corrected: here currentCart is the inherited widget itself, not its list as in the Inventory (the book does not print the assignment). The ShoppingCart needs final ShoppingCartInheritedWidget currentCart = ShoppingCartInheritedWidget.of(context)!; at the top of build, as the runnable copy does, so that currentCart.itemsInCart and the getters below resolve.

It is easy enough to get the total number of items in the cart by getting the length of the list. It is also easy enough to clear the cart by passing an empty list to the onCartUpdated method. While we could certainly do some math here to figure out the total cost of all items in the cart, it might make more sense to do that in our inherited widget. In fact, let us write a little getter method to do just that:

Example 9.17 · Example 9.17.dart
double get totalCost {
  double price = 0;
  for (Item item in itemsInCart) {
    price += item.cost;
  }

  return price;
}

When we put this inside our inherited widget, we can simply call the property of the inherited widget to get the value. In practice, that would look like the following: ShoppingCartInheritedWidget.of(context)!.totalCost. Since we already assigned the inherited widget to a variable, we can use that same variable to get the total cost:

Example 9.18 · Example 9.18.dart
Text('Total Cost: \$${currentCart.totalCost.toStringAsFixed(2)}'),

With that, we have checked another item off our TODO list. Looking at what is left of our TODOs, we know that we need to figure out how many unique items are in the cart. Just like we did with the totalCost getter, we can write a getter that will iterate over the items in our cart and return a unique list:

Example 9.19 · Example 9.19.dart
List<Item> get uniqueItemsInCart {
  final List<Item> unique = [];
  for (Item item in itemsInCart) {
    if (!unique.contains(item)) {
      unique.add(item);
    }
  }
  return unique;
}

Once we have got a method to tell us what the unique items in the list are, we have everything we need to finish off our ShoppingCart:

Example 9.20 · Example 9.20.dart
ListView.builder(
  shrinkWrap: true,
  physics: const ClampingScrollPhysics(),
  itemCount: currentCart.uniqueItemsInCart.length,
  itemBuilder: (context, i) => Card(
    child: ListTile(
      leading: Text(
        currentCart.itemsInCart
                .where((element) =>
                    element == currentCart.uniqueItemsInCart[i])
                .length
                .toString() +
            '×',
      ),
      title: Text(
        currentCart.itemsInCart
            .firstWhere((element) =>
                element == currentCart.uniqueItemsInCart[i])
            .name,
      ),
      subtitle: Text(
          '\$${currentCart.itemsInCart[i].cost.toStringAsFixed(2)}'),
    ),
  ),
),
Corrected: the subtitle reads the price from itemsInCart[i], but i counts the rows of unique items. Once the cart holds a duplicate, a row can show another item's price: with Shirt, Shirt, Pants in the cart, the Pants row shows $12.99. Use currentCart.uniqueItemsInCart[i].cost, as the runnable copy does. The same applies to the Provider version below.

Runnable copy: examples/flutter_for_jobseekers_ch09/lib/inherited_widget/main.dart

And that is how to manage app state using an inherited widget. As you can see, it takes quite a bit of work to use this method. There are many packages out there that wrap up all the complexity involved in using an inherited widget in this way to manage app state and make it much more straightforward to use. In the next section, we are going to look at Provider, which aims to do just that.

Using Provider to manage app state

The Provider package is a simple app state management solution that does all the heavy lifting of creating an inherited widget for us. To get started, add the latest version of Provider to your pubspec and run flutter pub get.

Provider offers a bunch of extra functionalities that we are not going to cover here, so be sure to read over the documentation to familiarize yourself with the best practices and any functionality we do not cover.

The ChangeNotifier

Once you have imported Provider into your code, we can start using it. First, let us set up a provider for our shopping cart. This time, instead of creating an inherited widget, we will extend the ChangeNotifier class, which will trigger rebuilds when parts of the widget change (such as the items in our cart):

Example 9.21 · Example 9.21.dart
class ShoppingCartProvider extends ChangeNotifier {
  final List<Item> _itemsInCart = [];

  UnmodifiableListView<Item> get itemsInCart =>
      UnmodifiableListView(_itemsInCart);

  double get totalCost {
    double price = 0;
    for (Item item in _itemsInCart) {
      price += item.cost;
    }

    return price;
  }

  List<Item> get uniqueItemsInCart {
    final List<Item> unique = [];
    for (Item item in _itemsInCart) {
      if (!unique.contains(item)) {
        unique.add(item);
      }
    }
    return unique;
  }

  void add(Item item) {
    _itemsInCart.add(item);
    notifyListeners();
  }

  void emptyCart() {
    _itemsInCart.clear();
    notifyListeners();
  }
}

You will notice that a lot of the code is the same as our inherited widget version. In fact, our two getters, totalCost and uniqueItemsInCart, are the same. What is different, however, is how we access the items in the cart, add items to the cart, and empty the cart.

UnmodifiableListView

To get the items in the cart, this time, we have the getter itemsInCart, which returns an UnmodifiableListView<Item> value. An UnmodifiableListView is, as the name implies, a representation of an existing list that cannot be modified. We will get to why that is later.

The cart moves out of MyApp

Also note that we were able to move the list holding our cart into this widget instead of using a stateful widget for our MyApp. It makes a lot more sense to have it here, since this is what is holding the actual cart state.

add and emptyCart

Finally, we have two methods for adding and clearing the cart. They are self-explanatory but have a new concept to look at: notifyListeners().
Corrected:ShoppingCartProvider is not a widget. ChangeNotifier is "a class that can be extended or mixed in that provides a change notification API using VoidCallback for notifications" (flutter/flutter, n.d.); the rebuilds come from the widgets that listen to it, such as the Consumers below. UnmodifiableListView comes from dart:collection, which the file must import.

Adding the provider to the widget tree

We have not come across the notifyListeners() method call before. To explain it, we will first need to add our ShoppingCartProvider to the widget tree:

Example 9.22 · Example 9.22.dart
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => ShoppingCartProvider(),
      child: const MyApp(),
    ),
  );
}

The ChangeNotifierProvider widget, which is part of the Provider package, will listen for events triggered by the notifyListeners method and rebuild itself accordingly.

Without a listener of some sort (of which ChangeNotifierProvider is but one), calling notifyListeners has no effect.

A simpler MyApp

So, how else does this change our app? Well, for starters, it significantly simplifies our MyApp widget. As previously mentioned, we no longer need to hold the app state, so we can use a stateless widget. Plus, since the cart is now in our ShoppingCartProvider, we do not need to have a variable for it there, which also means we do not need any sort of method to update the cart right here. Look at how much cleaner that makes our widget:

Example 9.23 · Example 9.23.dart
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: const [
              Inventory(),
              ShoppingCart(),
            ],
          ),
        ),
      ),
    );
  }
}

Consuming the provider

It also simplifies both the Inventory and ShoppingCart widgets. The Inventory, for example, becomes a consumer of the ShoppingCartProvider. The Consumer widget comes from the Provider package and takes in a builder, which provides the BuildContext, the Provider, and an optional child widget.

The child parameter can be used to improve performance by limiting the number of widgets that redraw. See the documentation for more details.

This is what our new Inventory looks like, once we have updated it to use the provider we created:

Example 9.24 · Example 9.24.dart
class Inventory extends StatelessWidget {
  const Inventory({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<ShoppingCartProvider>(
      builder:
          (BuildContext context, ShoppingCartProvider cart, Widget? child) {
        return ListView(
          shrinkWrap: true,
          physics: const ClampingScrollPhysics(),
          children: [
            Text(
              'Inventory',
              style: Theme.of(context).textTheme.displayMedium,
            ),
            ListView.builder(
              shrinkWrap: true,
              physics: const ClampingScrollPhysics(),
              itemCount: inventory.length,
              itemBuilder: (BuildContext context, int i) => Card(
                child: ListTile(
                  title: Text(inventory[i].name),
                  subtitle: Text('\$${inventory[i].cost.toStringAsFixed(2)}'),
                  trailing: IconButton(
                    icon: const Icon(Icons.add_shopping_cart),
                    onPressed: () => cart.add(inventory[i]),
                  ),
                ),
              ),
            ),
          ],
        );
      },
    );
  }
}

Note how this changes our onPressed method of the add to cart button. We are calling the method inside the provider we created when we tap the button. It is much cleaner than passing in a callback function and dealing with the change higher in the widget tree.

Like how using Provider has simplified the Inventory, it also simplifies the ShoppingCart:

class ShoppingCart extends StatelessWidget {
  const ShoppingCart({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<ShoppingCartProvider>(
      builder:
          (BuildContext context, ShoppingCartProvider cart, Widget? child) =>
              ListView(
        shrinkWrap: true,
        physics: const ClampingScrollPhysics(),
        children: [
          Text(
            'Shopping Cart',
            style: Theme.of(context).textTheme.displayMedium,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Text('Items in Cart: ${cart.itemsInCart.length}'),
              Text('Total Cost: \$${cart.totalCost.toStringAsFixed(2)}'),
              OutlinedButton.icon(
                label: const Text('Clear cart'),
                icon: const Icon(Icons.remove_shopping_cart),
                onPressed: () => Provider.of<ShoppingCartProvider>(
                  context,
                  listen: false,
                ).emptyCart(),
              ),
            ],
          ),
          ListView.builder(
            shrinkWrap: true,
            physics: const ClampingScrollPhysics(),
            itemCount: cart.uniqueItemsInCart.length,
            itemBuilder: (context, i) => Card(
              child: ListTile(
                leading: Text(
                  '${cart.itemsInCart.where((e) => e == cart.uniqueItemsInCart[i]).length} ×',
                ),
                title: Text(
                  cart.itemsInCart
                      .firstWhere((e) => e == cart.uniqueItemsInCart[i])
                      .name,
                ),
                subtitle:
                    Text('\$${cart.itemsInCart[i].cost.toStringAsFixed(2)}'),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Runnable copy: examples/flutter_for_jobseekers_ch09/lib/provider/main.dart (the subtitle uses cart.uniqueItemsInCart[i], see the correction in the inherited widget section)

Take note of the onPressed parameter of the clear cart button. This time, rather than call the emptyCart method on the cart object, we have chosen to reference the Provider via context. We did this so that we can pass in listen: false because we do not need to rebuild the button after running the method. This code was added as an illustration and only trivially changes the behavior of the application, if at all.

Outside of that change, everything else should be completely familiar. It is also all the last of the changes we need to use Provider to manage our app state.

Using Provider means we had to write far less code than with the inherited widget. We no longer have a stateful widget anywhere and we are not passing methods around to the different child widgets.
Provider is an excellent solution if you need a simple app state management system. However, it lacks certain functionality that might be useful, such as providing different states (think an adding to cart state followed by an added to cart state or an error adding to cart state that might be useful when communicating with an API). For that, let us look at a more powerful solution: BLoC.

Using BLoC's Cubit to manage app state

BLoC, or business logic component, is an extremely popular app state management solution. The goal behind BLoC is to abstract out the logic of the app from the presentation of the app while still allowing you to maintain app state.

To understand BLoC, we first need to look at the concept of a Cubit, which is akin to a lite version of BLoC. Both BLoC and Cubit are supplied by the flutter_bloc package. To get started, first, add the package to your pubspec, then import it into your app.

The state class and the Cubit

A Cubit will feel very familiar since most of what is in a Cubit is what you would find in a Provider. The Cubit comes in two parts:

The state object

Holds the current state of the Cubit. It can hold other pieces of information, but it does not do any processing.

The Cubit itself

Where the processing happens: it reads the current state and emits new ones.

First, look at the state class:

Example 9.25 · Example 9.25.dart
class CartState {
  final List<Item> itemsInCart;

  CartState(this.itemsInCart);
}

That is all there is to the state object. It can hold other pieces of information, but it does not do any processing. That is where our Cubit comes into play:

Example 9.26 · Example 9.26.dart
class ShoppingCartCubit extends Cubit<CartState> {
  ShoppingCartCubit() : super(CartState([]));

  double get totalCost {
    double price = 0;
    for (Item item in state.itemsInCart) {
      price += item.cost;
    }

    return price;
  }

  List<Item> get uniqueItemsInCart {
    final List<Item> unique = [];
    for (Item item in state.itemsInCart) {
      if (!unique.contains(item)) {
        unique.add(item);
      }
    }
    return unique;
  }

  void add(Item item) {
    final List<Item> updatedCart = state.itemsInCart..add(item);

    emit(CartState(updatedCart));
  }

  void clearCart() {
    emit(CartState([]));
  }
}

Most of this should be very familiar to you at this point. The parts that are new are going to be where we reference state to get at the itemsInCart variable, the double-dot operator on Line 24, and the emit() statements.

The state variable is managed by Cubit and points to that CartState class we created earlier. Each time we want to update the cart, the old CartState object is tossed out and replaced by a brand-new one. In order to use that object elsewhere in the app, we need to put a bow on it and send it off into the world by calling the emit() method on it.

Cascade notation

As for the double-dot operator: this is Dart's cascade notation. This is a super useful shortcut that lets you perform multiple operations on the same item. Say, for example, you wanted to progressively build a new Color. We can start with a base Color, then change it one step at a time:

Example 9.27 · Example 9.27.dart
Color test = const Color(0xFFFFFFFF)
  ..withAlpha(128)
  ..withBlue(100)
  ..withGreen(20)
  ..withRed(72);

It is a silly example to be sure, but compare that to the alternative (but also technically correct) way of accomplishing the same task:

Example 9.27 · Example 9.27.dart
Color test = const Color(0xFFFFFFFF);
test = test.withAlpha(128);
test = test.withBlue(100);
test = test.withGreen(20);
test = test.withRed(72);

As you can see, the cascade notation is a wonderful time-saving utility. Ok, back to Cubit and BLoC.

Corrected: the two versions do not do the same thing. A cascade operates on the original object, "ignoring any values that might be returned" (Dart, n.d.). Color is immutable, and withAlpha, withBlue and the others return a newColor, so the cascade version leaves test as 0xFFFFFFFF (white), while the second version ends with 0x80481464. Cascades suit methods that change the object they are called on, such as List.add in the Cubit above.

Providing and consuming the Cubit

Now that we have a Cubit and state class built, we need to provide access to them in the widget tree in the exact same way we did for Provider. The only difference is that we are going to use a BlocProvider class instead of a ChangeNotifierProvider:

Example 9.28 · Example 9.28.dart
void main() {
  runApp(
    BlocProvider(
      create: (context) => ShoppingCartProvider(),
      child: const MyApp(),
    ),
  );
}

Companion code: Example 9.28 has create: (context) => ShoppingCartCubit(), the corrected form.

Corrected:create must return the Cubit, ShoppingCartCubit(). ShoppingCartProvider is the Provider version's ChangeNotifier, and BlocProvider does not accept it: the analyzer reports that it "can't be assigned to the parameter type StateStreamableSource<Object?> Function(BuildContext)".

Just like Provider's Consumer<T> class, we have a BlocBuilder<B, S> class:

Example 9.29 · Example 9.29.dart
class ShoppingCart extends StatelessWidget {
  const ShoppingCart({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ShoppingCartCubit, CartState>(
      builder: (BuildContext context, CartState cart) {
        return ...
      }
    );
  }

This gives us access to the state object via the cart variable, assigned on Line 7. So, we could access the items in our cart by doing something like this:

Example 9.30 · Example 9.30.dart
Text('Items in Cart: ${cart.itemsInCart.length}'),

Since our cart state object only holds the list of items in the cart, we need another way to get information out of the Cubit. Luckily, we can access it via the BuildContext:

Example 9.30 · Example 9.30.dart
final List<Item> uniqueItemsInCart = context.read<ShoppingCartCubit>().uniqueItemsInCart;

Or if we want to add something to the cart, we could use the same logic:

Example 9.30 · Example 9.30.dart
IconButton(
  icon: const Icon(Icons.add_shopping_cart),
  onPressed: () => context.read<ShoppingCartCubit>().add(inventory[i]),
),
So, that is Cubit in a nutshell. See if you can update the Provider example to use a Cubit. The process should be quite straightforward with minimal challenges. Once you have got it working, or whenever you feel ready, we will dig into BLoC.

Runnable copy: examples/flutter_for_jobseekers_ch09/lib/cubit/main.dart (one solution to the exercise: the book does not print the full Cubit app; it is assembled from the fragments above and the publisher's companion Example 9.30)

Using BLoC to manage app state

While Cubit is great for simple app state management, sometimes you just need something more. BLoC is broken down into three parts:

The BLoC

Processes events and emits states.

State objects

What the UI is built from.

Events

What the UI sends to the BLoC.

Base classes, states and events

Let us start building some of these out so you can see what we are talking about, starting with defining a couple of base classes. We will not use these directly, but we will extend them to build the rest of our events and states:

Example 9.31 · Example 9.31.dart
@immutable
abstract class ShoppingCartEvent {}

@immutable
abstract class ShoppingCartState {}

Next, let us create a couple of possible states for the app to be in; first, an initial state where our cart is empty, then a state where we have items in the cart. While we are at it, let us create a waiting state that we can use later when we mimic the delay of calling an API and waiting for a response:

Example 9.31 · Example 9.31.dart
class Initial extends ShoppingCartState {
  Initial() : super();
}

class CartWithItems extends ShoppingCartState {
  final List<Item> itemsInCart;
  CartWithItems({required this.itemsInCart}) : super();
}

class Waiting extends ShoppingCartState {
  Waiting() : super();
}

Now that we have some states, let us create the events we will be using. Our app allows us to perform two actions: (1) add an item to the cart and (2) clear the cart contents. Let us create an event for each of those:

Example 9.31 · Example 9.31.dart
class AddItemToCart extends ShoppingCartEvent {
  final Item item;
  AddItemToCart({required this.item});
}

class ClearCart extends ShoppingCartEvent {
  ClearCart();
}

Finally, we can build our basic BLoC using these event and state objects:

Example 9.31 · Example 9.31.dart
class ShoppingCartBloc extends Bloc<ShoppingCartEvent, ShoppingCartState> {
  ShoppingCartBloc() : super(Initial()) {
    on<ShoppingCartEvent>((event, emit) {
      // TODO: implement event handler
    });
  }
}

From event to state

The general idea of how this will operate:

The BLoC starts in a state

The BLoC is created and generates a state (the super(Initial()) tells us that the state it starts with is Initial()).

An interaction sends an event

Some sort of interaction will send an event to the BLoC.

The BLoC emits states

The BLoC will process that event and emit one or more states.

Let us walk through this each step of the way. When the BLoC is initialized, the state is Initial(). Next, the user taps the add item to cart button, which looks like the following:

Example 9.32 · Example 9.32.dart
IconButton(
  icon: const Icon(Icons.add_shopping_cart),
  onPressed: () => context.read<ShoppingCartBloc>().add(
        AddItemToCart(
          item: inventory[i],
        ),
      ),
),

An event is added to the BLoC. That event, AddItemToCart, has a required item property, which is where we pass in the item we want to add to the cart. Next, the BLoC will process that event and emit a new state. Let us update the BLoC accordingly, to add the item to the cart and process the event:

Example 9.33 · Example 9.33.dart
class ShoppingCartBloc extends Bloc<ShoppingCartEvent, ShoppingCartState> {
  final List<Item> _itemsInCart = <Item>[];

  ShoppingCartBloc() : super(Initial()) {
    on<AddItemToCart>((event, emit) {
      _itemsInCart.add(event.item);
      emit(CartWithItems(itemsInCart: _itemsInCart));
    });
  }
}

This will emit a state that we can build the UI based upon. We will look at how to do that in just a moment, but first, let us add that perceived delay to mimic the API call and add the rest of the functionality to our BLoC which brings it up to par with what we have been working with in other state management solutions:

Example 9.34 · Example 9.34.dart
class ShoppingCartBloc extends Bloc<ShoppingCartEvent, ShoppingCartState> {
  final Cart _itemsInCart = <Item>[];

  ShoppingCartBloc() : super(Initial()) {
    on<AddItemToCart>((event, emit) async {
      emit(Waiting());
      await Future.delayed(const Duration(seconds: 2));
      itemsInCart.add(event.item);
      emit(CartWithItems(itemsInCart: _itemsInCart));
    });
    on<ClearCart>((event, emit) {
      _itemsInCart.clear();
      emit(Initial());
    });
  }

  double get totalCost {
    double price = 0;
    for (Item item in _itemsInCart) {
      price += item.cost;
    }

    return price;
  }

  Cart get uniqueItemsInCart {
    final Cart unique = [];
    for (Item item in _itemsInCart) {
      if (!unique.contains(item)) {
        unique.add(item);
      }
    }
    return unique;
  }
}

Companion code: Example 9.34 has the underscore, _itemsInCart.add(event.item), but it does not define Cart either.

Corrected: this version does not compile. Cart is used as a type but never defined (the analyzer reports Undefined class 'Cart'); the runnable copy adds typedef Cart = List<Item>;, a typedef like the ones above. itemsInCart.add(event.item) is missing the underscore: the BLoC has no itemsInCart, only _itemsInCart.
This BLoC has everything we need to build the rest of the application. Note how the event handler for adding an item to the cart emits multiple states. This is something you could also do with, say, Cubit. It allows us to build more dynamic interfaces for users by expressing to them the current state of the application.

Building the UI from the state

Once you have updated your BlocProvider to provide this new BLoC and the BlocBuilder to use the new BLoC and state, we can update the variables to match. As an example:

Example 9.35 · Example 9.35.dart
class ShoppingCart extends StatelessWidget {
  const ShoppingCart({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ShoppingCartBloc, ShoppingCartState>(
      builder: (BuildContext context, ShoppingCartState state) {
        final Cart uniqueItemsInCart =
            context.read<ShoppingCartBloc>().uniqueItemsInCart;
        final double totalCost = context.read<ShoppingCartBloc>().totalCost;
        ...
      };
  }
}

This is where things start to get interesting, though. We can use the state variable to build different widgets depending on the current state of the application.

Initial

If there is nothing in the cart, we have no reason to show the cart details or clear button. Instead, we might want to tell the user that their cart is empty.

Waiting

If we are waiting for the API to finish (that is, we are in a Waiting state), we might want to show a progress indicator.

CartWithItems

The cart details: the count, the total cost, the clear cart button and the items.
We just need to have a conditional based on what type of state the state is. That is why we created a base state class and extended it: all the states we created are still, technically, the base state.

When all is said and done, here is what the complete ShoppingCart looks like using the BLoC:

Example 9.35 · Example 9.35.dart
class ShoppingCart extends StatelessWidget {
  const ShoppingCart({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ShoppingCartBloc, ShoppingCartState>(
      builder: (BuildContext context, ShoppingCartState state) {
        final Cart uniqueItemsInCart =
            context.read<ShoppingCartBloc>().uniqueItemsInCart;
        final double totalCost = context.read<ShoppingCartBloc>().totalCost;

        return ListView(
          shrinkWrap: true,
          physics: const ClampingScrollPhysics(),
          children: [
            Text(
              'Shopping Cart',
              style: Theme.of(context).textTheme.displayMedium,
            ),
            if (state is Initial) const Text('Your cart is empty.'),
            elseif (state is Waiting)
              Column(
                children: const [
                  CircularProgressIndicator(),
                  Text('Please wait while we update your cart.'),
                ],
              ),
            if (state is CartWithItems)
              Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Text('Items in Cart: ${state.itemsInCart.length}'),
                      Text('Total Cost: \$${totalCost.toStringAsFixed(2)}'),
                      OutlinedButton.icon(
                        label: const Text('Clear cart'),
                        icon: const Icon(Icons.remove_shopping_cart),
                        onPressed: () =>
                            context.read<ShoppingCartBloc>().add(
                                  ClearCart()
                                ),
                      ),
                    ],
                  ),
                  ListView.builder(
                    shrinkWrap: true,
                    physics: const ClampingScrollPhysics(),
                    itemCount: uniqueItemsInCart.length,
                    itemBuilder: (context, i) {
                      return Card(
                        child: ListTile(
                          leading: Text(
                              '${state.itemsInCart.where((element) => element == uniqueItemsInCart[i]).length} ×'),
                          title: Text(uniqueItemsInCart[i].name),
                          subtitle: Text(
                              '\$${uniqueItemsInCart[i].cost.toStringAsFixed(2)}'),
                        ),
                      );
                    },
                  ),
                ],
              ),
          ],
        );
      },
    );
  }
}
Corrected: Dart has no elseif. The analyzer reads it as a call to an undefined function (The function 'elseif' isn't defined) and the line does not compile. In a collection if, the keyword is else if, so the Initial and Waiting lines become if (state is Initial) const Text('Your cart is empty.') else if (state is Waiting) Column(...), as the runnable copy does. The partial example above also closes the builder with }; instead of }, followed by );.

Runnable copy: examples/flutter_for_jobseekers_ch09/lib/main.dart (the complete BLoC app, with typedef Cart = List<Item>;)

BLoC is a very powerful state management solution, capable of empowering you, as a developer, to build expressive and dynamic interfaces that truly convey the current state of the application to a user.
It may be overkill in some scenarios where a Cubit or Provider would be just as effective, though. So, when choosing a state management solution, be sure to learn as much as you can about the different requirements for the task at hand and choose wisely.

Conclusion

We explored a lot of different methods of dealing with app state in this chapter. There is no single best solution, either. Each has its pros and cons.

This also was not an exhaustive list of all possible state management solutions that exist out there. We did not mention Flutter Hooks, Riverpod, Redux, MobX, or any of the other frameworks which are also quite popular.
Chances are, when you come into a project, there may already be a state management solution being used. Fortunately, by understanding the basics of things like using inherited widgets, Provider, or Cubit/BLoC to manage app state, you will not have much trouble following along with whatever state management solution you come across.

In the upcoming chapter, we are going to discuss concepts such as how to make an interface that lays itself out dynamically based on the available screen space. Plus, we are going to dig into some of the things you will need to know about building applications for different platforms.

Questions

  1. What is ephemeral state, and how is it different from app state?
  2. Why is a stateful widget not a good option for managing app state?
  3. If you have nested ListView widgets, how can you prevent the inner ListView from scrolling independently of its parent?
  4. What is the => operator used for? What are the benefits/drawbacks of using it?
  5. What is escaping? What characters might need to be escaped?
  6. What is interpolation?
  7. What is ValueChanged used for? How is it defined?
  8. What is a typedef?
  9. What is UnmodifiableListView used for?
  10. What are some differences and similarities between Provider, Cubit, and BLoC?
  11. What is cascade notation?
  12. What are some other popular app state management solutions?

Key terms

=> operator
Shorthand for returning a value.
App state
State which is maintained throughout the application.
Ephemeral state
State managed by a stateful widget.
Escaping
The process of using a backslash (\) to denote the following character should not be interpreted as a special character in a string.
Interpolation
A way of evaluating a variable or method and inserting the result directly in a string. Interpolation is denoted by the ${} characters, where the code inside the braces is to be evaluated.
typedef
A way to define a new type, on the fly, without creating a new class. ValueChanged, for example, is a typedef defined as: typedef ValueChanged<T> = void Function(T value)

Further reading

Dart's cascade notation

Learn more about Dart's cascade notation.

State management approaches

A list of state management approaches.

References

Copyright © 2026