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

Flutter向NumberFormat.simpleCurrency传空值触发isNegative错误如何解决

问题原因

NumberFormat.format() 方法不支持传入null参数,你现有代码中的 ?? "n/a" 是在format方法执行完成后才对返回值做的空判断,当 trxns.contractPrice 为null时,format方法已经在执行阶段抛出异常,后续的空判断逻辑不会被触发,因此会出现报错。

解决方案

根据你想要的展示效果可以选择两种处理方式:

  • 希望空值时展示 n/a:在调用format方法前先做非空判断,用三目运算符分支处理
TextSpan(
  text:
  '\nPrice: ${trxns.contractPrice != null ? NumberFormat.simpleCurrency().format(trxns.contractPrice) : "n/a"}\nStatus: ${trxns.trxnStatus ?? "n/a"}',
  style: TextStyle(
      fontWeight: FontWeight.w900,
      color: Colors.blueGrey),
)
  • 希望空值时默认展示0对应的货币格式(比如$0.00):直接在入参阶段做空值默认替换
TextSpan(
  text:
  '\nPrice: ${NumberFormat.simpleCurrency().format(trxns.contractPrice ?? 0)}\nStatus: ${trxns.trxnStatus ?? "n/a"}',
  style: TextStyle(
      fontWeight: FontWeight.w900,
      color: Colors.blueGrey),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 21:09:03