我正在尝试从服务器获取 JSON 响应,并在 ListView 中输出。
以下代码导致错误:
Future<List> getCurrencies() async {
String cryptoUrl =
"https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=my-key";
http.Response response = await http.get(Uri.parse(cryptoUrl));
return json.decode(response.body);
}
我应该返回什么以解决此错误?
我的 JSON 如下所示:
"data": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"num_market_pairs": 8933,
"date_added": "2013-04-28T00:00:00.000Z",
"tags": [
"mineable",
"pow",
"sha-256",
"store-of-value",
"state-channels",
"coinbase-ventures-portfolio",
"three-arrows-capital-portfolio",
"polychain-capital-portfolio",
"binance-labs-portfolio",
"arrington-xrp-capital",
"blockchain-capital-portfolio",
"boostvc-portfolio",
"cms-holdings-portfolio",
"dcg-portfolio",
"dragonfly-capital-portfolio",
"electric-capital-portfolio",
"fabric-ventures-portfolio",
"framework-ventures",
"galaxy-digital-portfolio",
"huobi-capital",
"alameda-research-portfolio",
"a16z-portfolio",
"1confirmation-portfolio",
"winklevoss-capital",
"usv-portfolio",
"placeholder-ventures-portfolio",
"pantera-capital-portfolio",
"multicoin-capital-portfolio",
"paradigm-xzy-screener"
]
}
答案 0 :(得分:0)
这是 jsonDecode
函数的原型 (它是 json.decode
的缩写)。
// dart:convert
dynamic jsonDecode(String source, {Object? Function(Object?, Object?)? reviver})
类型:动态函数(String,{Object? Function(Object?, Object?)? reviver})
它返回 dynamic
。因此,getCurrencies
的适当返回类型将是
Future<dynamic> getCurrencies()
或简单地
Future getCurrencies()
要处理 json:
void processJson(dynamic json) {
var x = json as Map<String, dynamic>;
print(x['data'][0]['name']); // 打印 'Bitcoin'
}