Flutter Fetch API



我试图从外部api获取数据,但我的屏幕显示此错误消息:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Null' is not a subtype of type 'bool'

我的屏幕代码是这样的:

class PricesScreen extends StatefulWidget {
const PricesScreen({super.key});
@override
State<PricesScreen> createState() => _PricesScreenState();
}
class _PricesScreenState extends State<PricesScreen> {
late Response response;
Dio dio = Dio();
var apidata;
bool error = false; //for error status
bool loading = false; //for data featching status
String errmsg = "";
getData() async {
String baseUrl = "https://economia.awesomeapi.com.br/last/USD-BRL";
Response response = await dio.get(baseUrl);
apidata = response.data;
print(response);
if(response.statusCode == 200){
if(apidata["error"]){
error = true;
errmsg  = apidata["msg"];
}
}else{
error = true;
errmsg = "Error while fetching data.";
}
}
@override
void initState() {
getData(); //fetching data
super.initState();
}

@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(8),
child: loading?
const CircularProgressIndicator() :
Container(
child:error?Text("Error: $errmsg"):
Column(
children:apidata["data"].map<Widget>((coin){
return CurrencyContainer(
name: coin["name"],
increase: coin["varBid"],
symbol: coin["code"],
value: coin["high"]
);
}).toList(),
)
)
);
}
}

我的打印消息显示来自api的数据:

{"USDBRL":{"code":"USD","codein":"BRL","name":"Dólar Americano/Real Brasileiro","high":"5.1856","low":"5.1856","varBid":"0.0004","pctChange":"0.01","bid":"5.1851","ask":"5.186","timestamp":"1669850610","create_date":"2022-11-30 20:23:30"}}

我试图访问数据为'apidata = response["USDBRL"]',但它显示错误:lib/screens/prices。dart:27:23:错误:操作符'[]'没有为类'Response'定义。

  • 'Response'来自'package:dio/src/Response'。飞镖 ' ('../../快速/颤振/共同/颤振/.pub-cache/托管/pub.dartlang.org/dio-4.0.6/lib/src/response.dart")。尝试将操作符更正为现有操作符,或定义'[]'操作符。apidata = response["USDBRL"];

如何在屏幕上显示数据?

您的问题是访问数据,要做到这一点,只需访问:

response.data['USDBRL']

您得到了错误,因为您试图从响应对象本身访问USDBRL。从api返回的数据应该在响应对象的data属性中。

if(apidata['error'])这会导致错误,因为apidata['error']是空的,不能用作bool

if(response.statusCode == 200){
error = false;
errmsg  = '';
}

,你可以用

访问数据
apidata['USDBRL']

相关内容

  • 没有找到相关文章

最新更新