在 flutter app 中将 null 传递给 NumberFormat.simpleCurrency

Passing null to NumberFormat.simpleCurrency in flutter app

我正在使用 NumberFormat.simpleCurrency 在我的 flutter 应用程序中格式化美元金额。如果 trxns.contractPrice 不为空,效果很好。当它为 null 时,我收到以下错误: getter 'isNegative' 被调用为 null。 接收者:空 尝试调用:isNegative

这是代码片段:

TextSpan(
                                  text:
                                  '\nPrice: ${NumberFormat.simpleCurrency().format(trxns.contractPrice) ?? 'n/a'}\nStatus: ${trxns.trxnStatus ?? 'n/a'}',
                                  style: TextStyle(
                                      fontWeight: FontWeight.w900,
                                      color: Colors.blueGrey),
                                )

我没能找到关于这个错误的任何信息。谁能帮我解决空值问题?

在格式

之前null检查contractPrice

样本:

Text(
'\nPrice: ${(contractPrice != null) ? NumberFormat.simpleCurrency().format(contractPrice) : 'n/a'}',
)

首先检查 traxns 值是否不为空,然后检查其 属性 或方法 contractPrice 是否不为空。现在,其中一件事情您得到的是 null,NumberFormat 中的 format 方法抛出了一个异常。一个可能的例子是:

TextSpan(
    text:'\nPrice: ${trxns!.contractPrice == null ? 'n/a' : NumberFormat.simpleCurrency().format(trxns.contractPrice)}\nStatus: ${trxns!.trxnStatus ?? 'n/a'}',
    style: TextStyle(fontWeight: FontWeight.w900, color: Colors.blueGrey),
);