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();
}
}
CCData
Model class here