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

我有三个文件,其中包含以下代码.

其中,我显示了所有列表项

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

推荐答案

您需要更新您的视图,因为列表中的数据已更改.如果您使用setState作为In,则在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);

Flutter相关问答推荐

在Flutter中,有没有一种方法可以点击页面到后面的页面?

文本未设置在集装箱摆动的中心

如何在FiRestore中正确编写OR查询

我怎样才能在Ffltter中显示html布局链接?

Flutter 文件拾取器Android SingleInstance模式它返回的文件路径为空

FOR回路中的Flutter 模型

StateNotifer正在riverpod中提供初始状态值(bool)

谷歌 map 在 flutter 应用程序中显示错误的当前位置

Flutter:我的应用程序是否需要包含退款购买?

如何获取flutter中gridview项目占用的高度和宽度?

Flutter 火焰相机抖动已弃用

无法从一个页面导航到下一个页面 (Flutter)

Flutter:如何在 bottomsheet 中创建一个日期 Select 器,如下图所示

Flutter - 如何将按钮对齐到行的右侧

如何对齐卡片小部件中的图标按钮?

Listview 如何转到下一行/新行?

如何使用 Row 和 Column 制作 L 形布局?

Flutter Widget 测试:无法使用 find.byWidget() 找到小部件

Flutter 本地通知在最新版本中不起作用

主题:ThemeData() Flutter