如何从购物车中删除商品?

时间:2021-03-12 02:36:26

标签: flutter dart

最近我关注了一个 Youtube 教程,其中展示了如何将产品添加到购物车。但在视频中,它没有展示如何从购物车中删除项目。视频链接:https://www.youtube.com/watch?v=K8d3qqbP3qk

ProductModel.dart

class ProductModel{
  String name;
  int price;
  String image;

  ProductModel(String name, int price, String image){
    this.name = name;
    this.price = price;
    this.image = image;
  }
}

ProductScreen.dart

import 'package:flutter/material.dart';

import '../ProductModel.dart';
import 'package:ecommerce_int2/models/product.dart';


class ProductScreen2 extends StatelessWidget {
  final ValueSetter<ProductModel> _valueSetter;

  ProductScreen2(this._valueSetter);

  List<ProductModel> products = [
    ProductModel("Grey Jacket", 100, 'assets/jacket_1.png'),
    ProductModel("Brown Pants", 60, 'assets/jeans_9.png'),
    ProductModel("Grey Pants", 50, 'assets/jeans_6.png'),
    ProductModel("Orange Pants", 70, 'assets/jeans_8.png'),
    ProductModel("Long Jeans", 80, 'assets/jeans_2.png'),
    ProductModel("Black and Blue Cap", 40, 'assets/cap_2.png'),
    ProductModel("Black Cap", 30, 'assets/cap_6.png'),
    ProductModel("Red Cap", 35, 'assets/cap_4.png'),
  ];

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: ListView.separated(
          itemBuilder: (context, index){
            return ListTile(
              leading: Image.asset(
                products[index].image,
                width: 100,
                height: 100,
                fit: BoxFit.fitWidth,
              ),
              title: Text(products[index].name),
              trailing: Text("\RM${products[index].price}", style: TextStyle(color: Colors.redAccent, fontSize: 20, fontWeight: FontWeight.w500),),
              onTap: (){
                _valueSetter(products[index]);
              },
            );
          },
          separatorBuilder: (context, index){
            return Divider();
          },
          itemCount: products.length
      ),
    );
  }
}

CheckoutScreen.dart

import 'package:flutter/material.dart';
import 'package:ecommerce_int2/screens/address/add_address_page.dart';
import 'package:device_apps/device_apps.dart';

class CheckoutScreen extends StatelessWidget {
  final cart;

  final sum;

  CheckoutScreen(this.cart, this.sum);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          ListView.separated(
            itemBuilder: (context, index){
              return ListTile(
                title: Text(cart[index].name),
                trailing: Text("\RM${cart[index].price}", style: TextStyle(color: Colors.redAccent, fontSize: 20, fontWeight: FontWeight.w500),),
                onTap: (){

                },
              );
            },
            separatorBuilder: (context, index){
              return Divider();
            },
            itemCount: cart.length,
            shrinkWrap: true,
          ),
          Divider(),
          Text("Total : \RM$sum", style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500), textAlign: TextAlign.right,),
          SizedBox(
            height: 20,
          ),
          Text("Remarks", style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),),
          TextFormField(
            decoration: InputDecoration(
              hintText: ('Example: Red Cap: Free Size, Grey Jacket: UK, M Size'),
            ),
            maxLines: 5,
          ),
          SizedBox(
            height: 50,
          ),
          RaisedButton(
            color: Theme.of(context).accentColor,
            child: Text('Buy Now',style: TextStyle(color: Colors.white, fontSize: 20)),
            onPressed: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (_) => AddAddressPage()));
            },
          ),
          RaisedButton(
            color: Theme.of(context).accentColor,
            child: Text('Try Out',style: TextStyle(color: Colors.white, fontSize: 20)),
            onPressed: () => DeviceApps.openApp('com.DefaultCompany.clothestryingfunction2'),
          ),
        ],
      ),
    );
  }
}

add_to_cart.dart

import 'package:ecommerce_int2/ProductModel.dart';
import 'package:ecommerce_int2/screens/CheckoutScreen.dart';
import 'package:ecommerce_int2/screens/ProductScreen.dart';
import 'package:flutter/material.dart';

class CartApp extends StatefulWidget {
  @override
  _CartAppState createState() => _CartAppState();
}

class _CartAppState extends State<CartApp> {
  List<ProductModel> cart = [];
  int sum = 0;

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: Text("Add To Cart"),
          bottom: TabBar(
            tabs: <Widget>[
              Tab(text: "Products",),
              Tab(text: "Cart",),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            ProductScreen2((selectedProduct){
              setState(() {
                cart.add(selectedProduct);//update
                sum = 0;
                cart.forEach((item){
                  sum = sum + item.price;
                });
              });
            }),
            CheckoutScreen(cart, sum),
          ],
        ),
      ),
    );
  }
}

目标是从购物车中移除所选商品,并从总和中减去所选商品的价格。谁能告诉我怎么做?

1 个答案:

答案 0 :(得分:0)

首先,您需要在 CheckoutScreen 中添加回调:

class CheckoutScreen extends StatelessWidget {
  final cart;
  final sum;
  final ValueSetter<ProductModel> _valueDeleter;


  CheckoutScreen(this.cart, this.sum, this._valueDeleter);
  ...

之后,在TabBarView中的CartApp中使用时添加回调函数:

CheckoutScreen(cart, sum, (deleteProduct) {
  setState(() {
    
    // Use this loop instead of cart.removeWhere() to delete 1 item at a time 
    for (var i = 0; i < cart.length; i++) {
        if (cart[i].name == deleteProduct.name) {
          cart.removeAt(i);
          break;
       }
    }
    sum = 0;
    cart.forEach((item) {
      sum = sum + item.price;
    });
  });
}),

最后,在 ListTile 中的 CheckoutScreen 中添加一个按钮以启动 delete 操作(为了简单起见,我在这里使用了 Row 中的 title ):

ListTile(
  ... 
  title: Row(
    children: [
      IconButton(
        icon: Icon(Icons.delete),
        color: Colors.red,
        onPressed: () => _valueDeleter(cart[index]),
      ),
      Text(cart[index].name),
    ],
  ),
  trailing: Text(
  ...