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

im beginner in flutter. i have an error to get JSON response like this.

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

I've been looking for this problem in the forum and I found like this.

Map<String, dynamic> map = json.decode(response.body);
List<dynamic> data = map["dataKey"];
print(data[0]["name"]);

but I don't understand how to write the function. this is my code.

Future<Map> getData() async {
var response = await http.get(
    'https://api.batulimee.com/v1_ship/port_detail?port_id=${widget.list[widget.index] 
['port_id'].toString()}');
return json.decode(response.body) as Map<String, dynamic>;
}

FutureBuilder<Map>(
          future: getData(),
          builder: (context, snapshot) {
            if (snapshot.hasError) print(snapshot.error);
            return snapshot.hasData
                ? new Ports(
                    list: snapshot.data['data'],
                  )
                : new Container();
          },
        ),

class Ports extends StatelessWidget {
final List list;
Ports({this.list});

@override
Widget build(BuildContext context) {
return ListView.builder(
  scrollDirection: Axis.horizontal,
  shrinkWrap: true,
  itemCount: list.length,
  itemBuilder: (context, i) {
    return Card(
      child: Container(
        padding: EdgeInsets.all(8),
        color: Colors.red,
        child: Text(
          list[i]['port_website'].toString(),
          style: TextStyle(color: Colors.white, fontSize: 24),
        ),
      ),
    );
  },
);
}
}

and the error like this.

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

im sorry for asking the same question because i dont understand about it :(. thank you for helping

1 answer

  • answered 2020-10-16 05:14 abbas jafary

      //define your model in defineModel
      Map<int, defineModel> yourMap = {};
    

    and get method:

          Future<void> getFavoriteList() async {
            try {
              final response = await http.get('url');
              final extractedData = json.decode(response.body);
              if (extractedData == null) {
                return;
              }
              final Map<int, defineModel> loadedProducts = {};
            
              final lastExtract = extractedData['dataKey'];
                
              lastExtract.forEach((prodData) {
                loadedProducts.putIfAbsent(
                //you Must Define A UniqueKey in here
                  key,
                  () => defineModel(
                    key1: prodData['key1'],
                    key2: prodData['key2'],
                    key3: prodData['key3'],
                  ),
                );
              });        
              yourMap = loadedProducts;
            } catch (error) {
              throw (error);
            }
          }