值可能为空时的下标访问

问题描述 投票:0回答:1
Text(
  dataList[index]["merchant"]["merchant"] ?? "No Merchant",
  maxLines: 1,
  overflow: TextOverflow.ellipsis,
  style: const TextStyle(
      fontWeight: FontWeight.bold,
      color: Colors.black),
),

当文本可能为空时,进行列表理解的最佳方法是什么。我不想添加大量的 if, else 块。问题是,当

dataList[index]["merchant"]
为 null 时,flutter 引擎会出错,因为没有对应的下标。
??
运算符也不起作用,因为 flutter 引擎在显示无商家值之前就会出错。

dataList[index]["merchant"]
为 null 而不是已填充时,错误如下所示:

The following _TypeError was thrown building:
type 'String' is not a subtype of type 'int' of 'index'
flutter dart list-comprehension
1个回答
0
投票

从您上面给出的 JSON 数据来看,结构似乎是:列表>“商家”>列表>“商家”。要访问它,您可以使用以下命令:

(dataList[0]["merchant"] as List)[0]["merchant"]
© www.soinside.com 2019 - 2024. All rights reserved.