You need to enable JavaScript to run this app. 如何将数据库查询的商品总价和应付总金额显示在Flutter自定义按钮上?
优惠活动
大模型
产品
解决方案
定价
更多

如何将数据库查询的商品总价和应付总金额显示在Flutter自定义按钮上?

实现方案

1. 前置准备:拉取数据库数据并计算金额

你需要先从本地数据库(如sqflite)查询已存储的商品列表,累加计算商品总价、应付总金额,通过State管理这两个数值:

// 示例:商品数据实体类
class Product {
  final double price;
  final int count;
  Product({required this.price, required this.count});
}

// 示例:数据库查询商品列表方法
Future<List<Product>> getProductListFromDB() async {
  final db = await openDatabase('your_db_path.db');
  final List<Map<String, dynamic>> maps = await db.query('products');
  return List.generate(maps.length, (i) => Product(
    price: maps[i]['price'],
    count: maps[i]['count'],
  ));
}

// 在State类中定义存储金额的变量
double _totalProductPrice = 0.0;
double _totalPayable = 0.0;

// 页面初始化时拉取数据计算金额
@override
void initState() {
  super.initState();
  _loadAmountData();
}

Future<void> _loadAmountData() async {
  final productList = await getProductListFromDB();
  double total = 0.0;
  for (var p in productList) {
    total += p.price * p.count;
  }
  setState(() {
    _totalProductPrice = total;
    // 应付金额可根据需求叠加优惠、运费等计算,此处示例和商品总价一致
    _totalPayable = total;
  });
}

2. 调整布局展示两个金额按钮

你原有Row布局只放了一个总价按钮,可新增应付金额按钮,同时把计算好的金额拼接到按钮文本中即可:

Row(
  crossAxisAlignment: CrossAxisAlignment.center,
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    // 商品总价按钮
    Container(
      alignment: Alignment.bottomLeft,
      width: 150,
      padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
      child: CustomButton(
        btnTxt: '${getTranslated('total_amount', context)}: ${_totalProductPrice.toStringAsFixed(2)}元',
        backgroundColor: Theme.of(context).primaryColor,
        onTap: () {
          // 可选交互:点击按钮展示商品明细弹窗
        },
      ),
    ),
    // 新增应付总金额按钮
    Container(
      alignment: Alignment.bottomLeft,
      width: 180,
      padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
      child: CustomButton(
        btnTxt: '${getTranslated('payable_amount', context)}: ${_totalPayable.toStringAsFixed(2)}元',
        backgroundColor: Colors.redAccent,
        onTap: () {
          // 可选交互:点击按钮跳转到支付页
        },
      ),
    ),
  ],
)

3. 可选优化:CustomButton支持独立金额样式

如果你需要按钮内左边显示标题、右边单独显示金额(样式区分),可以修改CustomButton的child结构,不用纯文本拼接:

class CustomButton extends StatelessWidget {
  final Function? onTap;
  final String btnTxt;
  final Color? backgroundColor;
  final Icon? icon;
  // 新增独立金额参数
  final String? amountText;
  CustomButton({this.onTap, required this.btnTxt, this.backgroundColor, this.icon, this.amountText});

  @override
  Widget build(BuildContext context) {
    final ButtonStyle flatButtonStyle = TextButton.styleFrom(
      backgroundColor: onTap == null ? ColorResources.getGreyColor(context) : backgroundColor ?? Theme.of(context).primaryColor,
      minimumSize: Size(MediaQuery.of(context).size.width, 50),
      padding: const EdgeInsets.symmetric(horizontal: 8),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10),
      ),
    );

    return TextButton(
      onPressed: onTap != null ? () => onTap!() : null,
      style: flatButtonStyle,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(btnTxt,
              style: Theme.of(context).textTheme.headline3?.copyWith(color: ColorResources.COLOR_WHITE, fontSize: Dimensions.FONT_SIZE_DEFAULT)),
          if(amountText != null)
            Text(amountText!,
                style: Theme.of(context).textTheme.headline3?.copyWith(color: ColorResources.COLOR_WHITE, fontSize: Dimensions.FONT_SIZE_LARGE, fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }
}

优化后使用方式更灵活:

CustomButton(
  btnTxt: getTranslated('total_amount', context),
  amountText: '${_totalProductPrice.toStringAsFixed(2)}元',
  backgroundColor: Theme.of(context).primaryColor,
)

内容的提问来源于stack exchange,提问作者Metehan Gezer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 12:51:02