Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert json empty array in Flutter?

EDIT: after I check again, as this is a field within an object within a list, turns out somewhere in the list, one object does actually having "data": {}

Closed question. Thanks for helping.


I have a json field with contents of empty array:

{
  "data": [ ]
}

The problem is when I tried to put it into a list, it throws a fit.

List<dynamic> result = json["data"];

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

When I see it's "internal linked hash map", I thought then maybe I can use a Map. So I changed the receiver type as Map.

Map<String, dynamic> result = json["data"];

type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

Why is this happening?

The only way I can finally resolve this is by creating a type-inferred variable as an intermediate:

var temp = json["data"];
print("temp's runtime type: ${temp.runtimeType}");  // List<dynamic>
List<dynamic> result = temp;  // works

I know this is resolved using workaround for now, but I just want to know why the attempt above is error, and how can I straightly assign the json field content into explicitly-typed variable.

like image 256
Chen Li Yong Avatar asked Oct 24 '25 03:10

Chen Li Yong


1 Answers

At first, you just check your data is empty or not empty then assign the value to your map.

Map<String, dynamic> result;
if(json["data"]!=null && json["data"].isNotEmpty){
   result = json["data"];
}

like image 184
Jahidul Islam Avatar answered Oct 25 '25 18:10

Jahidul Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!