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

Flutter中如何将字符串变量转为int并执行数值运算?

问题解决方法

你的代码核心问题是直接对字符串执行+操作会做字符串拼接,而非数值求和,同时类型转换方式错误,还存在空指针风险。以下是修正后的实现:

修正要点

  • 用int.parse()或int.tryParse()将字符串转为整数,tryParse()更安全,能处理非数字输入的情况
  • 避免直接用!强制解包oneAmount?.amount,可设置默认值0
  • 完善输入验证,确保文本框输入是有效数字,而非仅判断非null

修正后的代码

void displayMessage() {
  // 解析文本框输入的金额,转为int,转换失败则取0
  int inputAmount = int.tryParse(amountController.text) ?? 0;
  // 处理Firestore获取的金额,空值则取0
  int firestoreAmount = oneAmount?.amount != null ? int.parse(oneAmount!.amount) : 0;
  
  // 数值求和
  int totalAmount = firestoreAmount + inputAmount;

  FirebaseFirestore.instance
      .collection("recharge")
      .doc("${loggedInUser.uid}")
      .set({
    "amount": totalAmount,
  });
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => const HomeScreen()),
  );
}

如果需要严格限制输入(仅允许有效数字),可以在转换前增加验证:

void displayMessage() {
  if (int.tryParse(amountController.text) == null) {
    // 这里可以添加提示,比如弹窗告知用户输入有效数字
    return;
  }
  
  int inputAmount = int.parse(amountController.text);
  int firestoreAmount = oneAmount?.amount != null ? int.parse(oneAmount!.amount) : 0;
  int totalAmount = firestoreAmount + inputAmount;

  FirebaseFirestore.instance
      .collection("recharge")
      .doc("${loggedInUser.uid}")
      .set({
    "amount": totalAmount,
  });
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => const HomeScreen()),
  );
}

内容的提问来源于stack exchange,提问作者Dasun Dola

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:00:58