Flutter Map in Cart Model, E Com app 12

As we said, List and Map play an important role in Flutter. While adding Cart items in an e-commerce app, we need a special Map method.

We’ll discuss that in a minute.

So far we have progressed and learned a few things while building the e-commerce app.

Most importantly, we have learned how to display product items by using the Provider package.

On the other hand, we have seen how we can avoid widget rebuilding by using Consumer for a particular child widget.

Firstly, let’s try to understand the structure of an e-commerce app. 

It must have a list of various products. Right? 

But users should be able to add them to cart. 

Secondly, while adding products to the cart, the number of items should display. 

At the very beginning, the number should be 0.

However, as users keep adding products the item numbers increase.

Finally, the user clicks the cart symbol, and sees all the added Cart items in one place.

If we want to achieve this mechanism, we need to make a Cart Model class first.

import 'package:flutter/foundation.dart';

class CartItems {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItems({
    required this.id,
    required this.title,
    required this.quantity,
    required this.price,
  });
}

class CartModel with ChangeNotifier {
  final Map<String, CartItems> _items = {};

  Map<String, CartItems> get items {
    return {..._items};
  }

  int get itemCount {
    return _items.length;
  }

  void addItem(
    String productId,
    double price,
    String title,
  ) {
    if (_items.containsKey(productId)) {
      // change quantity...
      _items.update(
        productId,
        (existingCartItems) => CartItems(
          id: existingCartItems.id,
          title: existingCartItems.title,
          price: existingCartItems.price,
          quantity: existingCartItems.quantity + 1,
        ),
      );
    } else {
      _items.putIfAbsent(
        productId,
        () => CartItems(
          id: DateTime.now().toString(),
          title: title,
          price: price,
          quantity: 1,
        ),
      );
    }
    notifyListeners();
  }
}

For example, we could have used a separate cart item in the Product class. 

Why?

Because, we have already used Change Notifier Provider and its “create” attribute passes the context and returns the Product model.

Therefore, it could have been easier to manage.

But we want to boost the performance of the Flutter app.

This method would not allow us to do that.

Why? Let’s try to understand.

Flutter Map putIfAbsent method

If we couple the Cart with Product, whenever users press the Cart item to add the products to the Cart, it rebuilds the whole widget.

On the other hand, if we use Cart as another Model class and use the Change Notifier, we can solve this problem.

As a result, a deeply-nested child widget will also listen to the change in the Cart Model without rebuilding the whole widget.

As a result, it enhances the app’s performance.

Although that part is okay, we have seen a new Map method: putIfAbsent() in the above code.

What does that mean?

Moreover, why do we need this method?

The logic is simple. 

Initially, every Cart is empty. Take a look at the following image.

Flutter Map Adding Cart items first example
Flutter Map Adding Cart items first example

At the top right hand corner of the AppBar, we see the Cart item is 0.

Therefore, when we press the Cart icon, it will first check whether the cart is empty or not? Right? 

The Map “putIfAbsent” method looks up the value of the Key. 

If it’s not there, it adds a new entry.

Let’s see one simple dart program.

void main() {
  
  Map<String, int> age = {'John': 36};
  
  print('The orignal map: $age');

  for (var key in ['Json', 'Abala', 'Rabi']) {
    age.putIfAbsent(key, () => key.length * 6);
  }
  print('The new map:$age');
}

// output:
The orignal map: {John: 36}
The new map:{John: 36, Json: 24, Abala: 30, Rabi: 24}

For that reason, when we add two products to the Cart, it immediately reflects.

Flutter Map two Cart items added
Flutter Map two Cart items added

In consequence we see the change in the AppBar. The number above the Cart icon changes from 0 to 2. 

Now there are a lot of things to come. 

Next, we’ll see how we can design the Cart model so that it works properly.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Python and Data Science

Twitter

Comments

3 responses to “Flutter Map in Cart Model, E Com app 12”

  1. […] In the previous section we have added a Cart Model. However, to nest a new Provider model class, we need to use the multi provider property of the Provider package. […]

  2. […] that we have added a Cart Model. However, to nest a new Provider model class, we need to use the multi provider property of the […]

  3. […] the above code we see that the button calls a method. As a result the method works upon the “Orders” model class, where we have defined the […]

Leave a Reply