I am trying to figure out how to handle JSON. the Problem is the error:

"Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in typecast ".

In the API example, there is an array, but no matter how I try to call it, nothing comes out. Ask for help. Also, please do not throw Slippers for grammar. I can 't write or speak English very well.

import 'package:flutter/material.dart';
import 'package:flutterapp/CCData.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class CCList extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    return CCListState();
  }
}

class CCListState extends State<CCList>{
  List<CCData> data = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('ЛОТОС-РЕСТОРАН'),
        ),
        body: Container(
            child: ListView(
              children: _buildList(),
            )
        ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.refresh),
        onPressed: () => _loadCC(),
      ),
    );
  }

  _loadCC() async{
    final response = await http.get('https://api.coincap.io/v2/assets?limit=4');
    if(response.statusCode == 200){
      //print(response.body);
      var allData = (json.decode(response.body) as Map)['data'] as Map<String, dynamic>;

      var ccDataList = List<CCData>();
      allData.forEach((String key, dynamic val){
        var record = CCData(name: val['name'],
            symbol: val['symbol'], rank: val['rank'], price: val['priceUSD']);
        ccDataList.add(record);
      });
      print(ccDataList);
    }

  }

  List<Widget> _buildList(){
    return data.map((CCData f) => ListTile(
      title: Text(f.symbol),
      subtitle: Text(f.name),
      leading: CircleAvatar(
          child: Text(f.rank.toString())),
      trailing: Text('\$${f.price.toString()}'),
    )).toList();
  }
}


Solution 1: Hưng Trịnh

I hope to help:

      var responseData= json.decode(response.body);
      var allData = responseData['data'] as List<dynamic>;
      List<CCData> ccDataList = [];
      allData.forEach((val){
        var record = CCData(name: val['name'],
            symbol: val['symbol'], rank: val['rank'], price: val['priceUSD']);
        ccDataList.add(record);
      });


Solution 2: Constantin N.

Your problem is at this line

var allData = (json.decode(response.body) as Map)['data'] as Map<String, dynamic>;

Obviously, (json.decode(response.body) as Map)['data'] returns a List of dynamic which can't be converted to Map (Not by this way) by casting.

To solve this, you should remove as Map<String, dynamic>

Then if you need to convert it to Map, you should write

var myMap = (json.decode(response.body) as Map)['data'].asMap();
print(myMap); //{0: map1,1: map2, 2: map3}

See official docs here