Subscript access when value may be null

47 Views Asked by At
Text(
  dataList[index]["merchant"]["merchant"] ?? "No Merchant",
  maxLines: 1,
  overflow: TextOverflow.ellipsis,
  style: const TextStyle(
      fontWeight: FontWeight.bold,
      color: Colors.black),
),

What is the best way to do list comprehension when your text might be null. I don't want to add a ton of if, else blocks. The issue is that when dataList[index]["merchant"] is null, the flutter engine errors out because there is no corresponding subscript. The ?? operator also doesn't work because the flutter engine errors out before it can display the no merchant value.

When dataList[index]["merchant"] is null instead of populated, the error looks like so:

The following _TypeError was thrown building:
type 'String' is not a subtype of type 'int' of 'index'
1

There are 1 best solutions below

1
Dhafin Rayhan On BEST ANSWER

From the JSON data that you give above, it seems like the structure is: List > "merchant" > List > "merchant". To access that, you can use this:

(dataList[index1]["merchant"] as List)[index2]["merchant"]

Replace index1 and index2 with the appropriate values. Make sure they don't exceed their corresponding list size.