繁体   English   中英

如何在颤动/ dart 中从购物车中删除商品

[英]How to remove item from cart in flutter/ dart

当您有单独的列表小部件时,如何从 flutter 的列表中删除购物车项目?

我有三个包含以下代码的文件。

carts.dart => 我在其中显示所有列表项

cart_list_item => 我在其中创建了一个小部件。

api_services.dart => 我从那里访问这些功能。

当购物车列表小部件和购物车列表位于单个文件中时,它正在工作。 但是为了增加购物车的数量,我不得不将它们分开。

CARTS.DART


class _CartsListState extends State<CartsList> {
  
  List cartList = [];
  getProducts() async {
    var resp = await http.get(
        Uri.parse("https://abc"));
    cartList.addAll(jsonDecode(resp.body));
     setState(()=>{});
    return jsonDecode(resp.body);
  }

  @override
  void initState() {
    super.initState();
    getProducts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(10),
        child: FutureBuilder(
          future: getProducts(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: cartList.length,
                itemBuilder: (BuildContext context, int index) {
                  var path = "https://abc";
                  var img = cartList[index]['image'] ?? 'default.png';
                  return MyCartListItem(
                      cartName: cartList[index]['english_name'],
                      cartQuantity: 2,
                      cartImage: path + img,
                      cartPrice: cartList[index]['mrp'].toString(),
                      cartIndex: 5);
                },
              );
            } else {
              return const LinearProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}

cart_list_item.dart

class MyCartListItem extends StatefulWidget {
  const MyCartListItem(
      {Key? key,
      required this.cartName,
      required this.cartQuantity,
      required this.cartImage,
      required this.cartPrice,
      required this.cartIndex})
      : super(key: key);
  final String cartName;
  final int cartQuantity;
  final String cartImage;
  final String cartPrice;
  final int cartIndex;

  @override
  State<MyCartListItem> createState() => _MyCartListItemState();
}

 @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(10.5),
        child: Row(children: [
          const SizedBox(
            width: 10,
          ),
          SizedBox(
            width: 70,
            height: 70,
            child: Image.network(widget.cartImage),
          ),
          const SizedBox(
            width: 50,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                // ignore: prefer_const_literals_to_create_immutables
                children: [
                  Container(
                    child: Text(
                      widget.cartName,
                      style: const TextStyle(
                        overflow: TextOverflow.clip,
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                ],
              ),
              const SizedBox(
                height: 7,
              ),
              Text(
                "Rs. ${widget.cartPrice}",
                style: const TextStyle(
                    fontWeight: FontWeight.bold, color: Colors.grey),
              ),
              const SizedBox(height: 10),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  InkWell(
                    onTap: () {
                      // setState() {
                      //   _itemCount--;
                      //   print(_itemCount);
                      // }
                    },
                    child: Container(
                        height: 30,
                        width: 30,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                          color: Colors.deepOrange[50],
                        ),
                        child: const Icon(
                          CupertinoIcons.minus,
                        )),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Text(_itemCount.toString()),
                  const SizedBox(
                    width: 10,
                  ),
                  InkWell(
                    // onTap: () {
                    //   setState() => {_itemCount++};
                    // },
                    child: Container(
                        height: 30,
                        width: 30,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                          color: Colors.deepOrange[50],
                        ),
                        child: const Icon(
                          CupertinoIcons.plus,
                        )),
                  ),
                  const SizedBox(
                    width: 15,
                  ),
                  InkWell(
                    onTap: () {
                      ApiServices.removeCartItem(0);
                      // setState(() {});
                      final snackBarData = SnackBar(
                        behavior: SnackBarBehavior.floating,
                        content: Row(
                          children: const [
                            Icon(Icons.shopping_bag),
                            SizedBox(
                              width: 10,
                            ),
                            Text('Product removed from cart !!!'),
                          ],
                        ),
                      );
                      ScaffoldMessenger.of(context).showSnackBar(snackBarData);
                    },
                    child: const Icon(
                      CupertinoIcons.trash,
                      color: Colors.red,
                    ),
                  )
                ],
              )
            ],
          )
        ]),
      ),
    );
  }
}

api services.dart *

 static removeCartItem(int indexNumber) async {
    cartList.removeAt(indexNumber);
  }

您需要更新视图,因为列表中的数据已更改。 如果您在 in 中使用setState ,请在CartListItem中实现回调,允许您在此回调中处理项目删除和更新视图。 它应该看起来像:

class MyCartListItem extends StatefulWidget {
  const MyCartListItem(
      {Key? key,
      required this.cartName,
      required this.cartQuantity,
      required this.cartImage,
      required this.cartPrice,
      required this.cartIndex,
      required this.onItemRemoved,
  }) : super(key: key);

  final String cartName;
  final int cartQuantity;
  final String cartImage;
  final String cartPrice;
  final int cartIndex;
  final Function onItemRemoved;

  @override
  State<MyCartListItem> createState() => _MyCartListItemState();
}

CartListItem

onTap: () => widget.onItemRemoved(index);

它已经回答了,但是如果您仍然有问题,我会尝试说清楚,如果不起作用,您可以稍后再问。

在您的 listViewBuilder 中:

return ListView.builder(
                itemCount: cartList.length,
                itemBuilder: (BuildContext context, int index) {
                  var path = "https://abc";
                  var img = cartList[index]['image'] ?? 'default.png';
                  return MyCartListItem(
                      cartName: cartList[index]['english_name'],
                      cartQuantity: 2,
                      cartImage: path + img,
                      cartPrice: cartList[index]['mrp'].toString(),
                      cartIndex: 5,
                      //------- this line -------------
                      removeFunction:(){
                       ApiServices.removeCartItem(index);
                      }
                 );
                },
              );

在您的卡片清单中:

class MyCartListItem extends StatefulWidget {
  const MyCartListItem(
      {Key? key,
      required this.cartName,
      required this.cartQuantity,
      required this.cartImage,
      required this.cartPrice,
      required this.cartIndex,
      required this.removeFuntion,
  }) : super(key: key);

  final String cartName;
  final int cartQuantity;
  final String cartImage;
  final String cartPrice;
  final int cartIndex;
  final Function removeFunction;

  @override
  State<MyCartListItem> createState() => _MyCartListItemState();
}
.... Rest OF code
// and here :
InkWell(
                onTap: () {
                  //------- THIS LINE -----:
                  widget.removeFunction;
                  //-----------------------
                  // setState(() {});
                  final snackBarData = SnackBar(
                    behavior: SnackBarBehavior.floating,
                    content: Row(
                      children: const [
                        Icon(Icons.shopping_bag),
                        SizedBox(
                          width: 10,
                        ),
                        Text('Product removed from cart !!!'),
                      ],
                    ),
                  );
                  ScaffoldMessenger.of(context).showSnackBar(snackBarData);
                },
                child: const Icon(
                  CupertinoIcons.trash,
                  color: Colors.red,
                ),
              )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM