Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>

I am trying to get the JSON response from the server and output it to the console.

Future<String> login() async {
    var response = await http.get(
        Uri.encodeFull("https://etrans.herokuapp.com/test/2"),
        headers: {"Accept": "application/json"});

    this.setState(() {
      data = json.decode(response.body);
    });


    print(data[0].name);
    return "Success!";
  }

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

What could be the reason?

like image 739
harunB10 Avatar asked Mar 30 '19 09:03

harunB10


2 Answers

Here are 2 common ways this could go wrong:

  1. If your response is a json array like

    [
        {
          key1: value1,
          key2: value2,
          key3: value3,
        },
        {
          key1: value1,
          key2: value2,
          key3: value3,
        },
    
        .....
    ] 
    

    Then, we use data[0]["name"], not data[0].name Unless we cast to an object that has the name property, we cannot use data[0].name

    We cast like this data = json.decode(response.body).cast<ObjectName>();

    ObjectName can be whatever object you want (Inbuilt or Custom). But make sure it has the name property

  2. If your response is a JSON object like

    {
        dataKey: [
          {
            key1: value1,
            key2: value2,
            key3: value3,
          } 
        ] 
    }
    

    Then json.decode will return a Map, not a List

    Map<String, dynamic> map = json.decode(response.body);
    List<dynamic> data = map["dataKey"];
    print(data[0]["name"]);
    
like image 86
Diyen Momjang Avatar answered Nov 14 '22 22:11

Diyen Momjang


You can use new Map<String, dynamic>.from(snapshot.value);

like image 80
AKASH MATHWANI Avatar answered Nov 14 '22 22:11

AKASH MATHWANI