类型'_InternalLinkedHashMap <String,dynamic>'不是类型'List <dynamic>'的子类型

时间:2020-10-16 04:25:30

标签: json flutter dart

我是初学者。我在获取这样的JSON响应时出错。

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

我一直在论坛中寻找这个问题,我发现是这样的。

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

但是我不明白如何编写函数。这是我的代码。

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),
        ),
      ),
    );
  },
);
}
}

和这样的错误。

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

很抱歉提出同样的问题,因为我对此不了解:(。感谢您的帮助

1 个答案:

答案 0 :(得分:0)

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

并获取方法:

      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);
        }
      }