Home > front end >  How to convert json empty array in Flutter?
How to convert json empty array in Flutter?

Time:11-26

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.

CodePudding user response:

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"];
}

CodePudding user response:

Dart compiler thinks that the result could be null so it is throwing errors, if you are sure that it will not be null then you could do this.

  //This json is of type Map<String, List<dynamic>>
  final json = {"data": []};

  if (json["data"] != null) {

    // i have used ! operator here after ["data"]
    List l = json["data"]!;

  }

or if you are not sure about the data then you can use what @Jahidul Islam has shown.

  • Related