You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter跨组件状态更新:点击CardDesign按钮更新main.dart的_totalAmount

Flutter子组件点击按钮更新父组件变量的解决方案

要实现CardDesign组件内的加减按钮点击后,更新main.dart中的_totalAmount变量,核心是通过回调函数完成子组件向父组件的数据传递,以下是具体修改步骤:

步骤1:给CardDesign添加回调函数参数

修改CardDesign.dart中的StatefulWidget类,新增用于通知价格变化的回调:

class CardDesign extends StatefulWidget {
  final itemTitle, itemColor, itemSize, itemUrl;
  int itemQuantity, showPrice = 0, itemPrice;
  // 新增回调,传递价格变化值(正数为加,负数为减)
  final Function(int)? onPriceChanged;

  CardDesign({
    super.key,
    required this.itemTitle,
    required this.itemColor,
    required this.itemSize,
    required this.itemQuantity,
    required this.itemPrice,
    required this.itemUrl,
    this.onPriceChanged,
  });

  @override
  State<CardDesign> createState() => _CardDesignState();
}

步骤2:在加减按钮点击时触发回调

修改CardDesign.dart中加减按钮的点击逻辑,更新数量的同时调用回调通知父组件:

// 减号按钮逻辑
IconButton(
  onPressed: () {
    if (widget.itemQuantity > 0) {
      widget.itemQuantity--;
      widget.showPrice -= widget.itemPrice;
      // 通知父组件减少对应金额
      widget.onPriceChanged!(-widget.itemPrice);
      setState(() {});
    }
  },
  icon: Icon(Icons.remove_rounded),
  color: Colors.black54,
  style: IconButton.styleFrom(
      elevation: 3,
      backgroundColor: Colors.white,
      shadowColor: Colors.white),
),

// 加号按钮逻辑
IconButton(
  onPressed: () {
    widget.itemQuantity++;
    widget.showPrice += widget.itemPrice;
    // 通知父组件增加对应金额
    widget.onPriceChanged!(widget.itemPrice);
    if (widget.itemQuantity == 5) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          surfaceTintColor: Colors.white,
          backgroundColor: Colors.white,
          title: Text(
            "Congratulations!",
            textAlign: TextAlign.center,
            style: TextStyle(fontWeight: FontWeight.w700),
          ),
          content: Text(
            "You have added \n5\n${widget.itemTitle} on your bag!",
            textAlign: TextAlign.center,
            style: TextStyle(fontWeight: FontWeight.w600),
          ),
          actions: [
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text(
                  "OKAY",
                  style: TextStyle(color: Colors.white),
                ),
                style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
              ),
            ),
          ],
        ),
      );
    }
    setState(() {});
  },
  icon: Icon(Icons.add_rounded),
  color: Colors.black54,
  style: IconButton.styleFrom(
      elevation: 2,
      backgroundColor: Colors.white,
      shadowColor: Colors.white),
),

步骤3:在父组件中接收回调更新总金额

修改main.dart中MyApp类的itemList,给每个CardDesign实例传递回调函数,实时更新_totalAmount:

List itemList = [
  CardDesign(
    itemTitle: "Pullover",
    itemColor: "Black",
    itemSize: "L",
    itemQuantity: 0,
    itemPrice: 51,
    itemUrl: "assets/images/pullover.png",
    onPriceChanged: (price) {
      setState(() {
        _totalAmount += price;
      });
    },
  ),
  CardDesign(
    itemTitle: "T-Shirt",
    itemColor: "Gray",
    itemSize: "L",
    itemQuantity: 0,
    itemPrice: 30,
    itemUrl: "assets/images/t_shirt.png",
    onPriceChanged: (price) {
      setState(() {
        _totalAmount += price;
      });
    },
  ),
  CardDesign(
    itemTitle: "Sport Dress",
    itemColor: "Black",
    itemSize: "M",
    itemQuantity: 0,
    itemPrice: 43,
    itemUrl: "assets/images/sport_dress.png",
    onPriceChanged: (price) {
      setState(() {
        _totalAmount += price;
      });
    },
  ),
];

可选优化:实时计算总金额

如果想避免回调累加可能出现的金额不一致问题,可以直接在父组件中通过遍历列表计算总金额,无需维护_totalAmount变量:

// 替换原有的Total amount行中的Text组件
Text(
  "${itemList.fold(0, (sum, item) => sum + (item.itemQuantity * item.itemPrice))}\$",
  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700),
)

内容的提问来源于stack exchange,提问作者MD. Sajid Hossain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:44:52