Flutter list clear, E Com App 17

We can use the Flutter List clear method in many ways. But the most convenient way, perhaps using the clear() method.

Why do we need this method? We need this method for many reasons, but in our E Commerce app, we need it to clear the cart.

In the beginning we have an introduction to the E Commerce App, that we have been building. We’ve been building it step by step, so that a beginner can understand each step. 

As a result, we have seen many changes. Not only that, we have discussed minute details like a Dart and Flutter List method “firstWhere()”.

In addition, we have discussed Modal route, abstract class, Dart mixin and extend, and many more.

From the beginning we’ve used a Material You theme that Flutter 3.0 supports. As a result, we have our first screenshot like the following which displays everything in dark.

Flutter app development, first step
Flutter app development, first step

Later as we progress, we have added many steps. Moreover, we have changed the theme from dark to light.

As a result now the app looks as follows.

Let's make some items favorite
Let’s make some items favourite

We have a cart model class in place. Let’s add some more methods to make it more functional. 

One of them is certainly to clear the list.

Why?

Because we can add the items to our cart. In one of the previous sections we have discussed this topic in detail.

Cart page where order can be placed
Cart page where order can be placed

In the above image we see a button “Order Now”.

For that reason, we need an Order model class first. 

Next, while pressing the button, we need to make two things happen at the same time.

Firstly, we need to place the order and the order page should display the output.

Next, we need to clear the cart.

Flutter and Dart List clear method

For example, let’s imagine a list like below. 

void main(){
  // Create list name
  List name = ['John', 'Json', 'Maria', 'James'];

  // Display result
  print('The elements in the list: $name');

  // Returns list length
  print('The list length:${name.length}');

  // remove items in the list
  // using clear()
  name.clear();

  // Returns list length
  print('The list length:${name.length}');
  
}

We can expect the output, because the code explains itself.

The elements in the list: [John, Json, Maria, James]
The list length:4
The list length:0

Now we can apply the same logic to our Flutter E Commerce app. 

Since we already have a Cart model in place, we can add one extra method in it to clear the list.

import 'package:flutter/foundation.dart';

class CartItems with ChangeNotifier {
  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 {
  Map<String, CartItems> _items = {};

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

  int get itemCount {
    return _items.length;
  }

  double get totalAmount {
    var total = 0.0;
    _items.forEach((key, cartItem) {
      total += cartItem.price * cartItem.quantity;
    });
    return total;
  }

  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();
  }

  void removeItem(String productId) {
    _items.remove(productId);
    notifyListeners();
  }

  void clear() {
    _items = {};
    notifyListeners();
  }
}

As we have the “Order Now” button in our cart page, we can add the Flutter list clear method to the “onPressed” void callback Function property.

Let’s see the Cart page where we can place the order and clear the cart at the same time.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/cart_model.dart';

import '../controllers/cart_item.dart';
import '../models/orders.dart';

class CartScreen extends StatelessWidget {
  static const routeName = '/cart';

  const CartScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final cart = Provider.of<CartModel>(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text('Your Cart'),
      ),
      body: Column(
        children: <Widget>[
          Card(
            margin: const EdgeInsets.all(15),
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  const Text(
                    'Total',
                    style: TextStyle(fontSize: 20),
                  ),
                  const Spacer(),
                  Chip(
                    label: Text(
                      '\$${cart.itemCount}',
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.error,
                      ),
                    ),
                    backgroundColor: Theme.of(context).primaryColor,
                  ),
                  TextButton(
                    child: Text(
                      'ORDER NOW',
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.outline,
                      ),
                    ),
                    onPressed: () {                      
                      cart.clear();
                    },
                  )
                ],
              ),
            ),
          ),
          const SizedBox(height: 10),
          Expanded(
            child: ListView.builder(
              itemCount: cart.items.length,
              itemBuilder: (ctx, i) => CartItem(
                cart.items.values.toList()[i].id,
                cart.items.keys.toList()[i],
                cart.items.values.toList()[i].price,
                cart.items.values.toList()[i].quantity,
                cart.items.values.toList()[i].title,
              ),
            ),
          )
        ],
      ),
    );
  }
}

Next we’ll work on the Order model class. In addition we will see how we can place the order.

So stay tuned.

Do you want to clone and run the app on your local machine? Please visit this branch of GitHub Repository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

TensorFlow, Machine Learning, AI and Data Science

Twitter

Comments

Leave a Reply