我试图从外部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”]“的形式访问数据,但显示错误:库/屏幕/价格。dart:27:23:错误:没有为类“Response”定义运算符“[]”。
- “响应”来自“package:dio/src/response.dart”('../../snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/dio-4.0.6/lib/src/response.dart')。请尝试将该运算符更正为现有运算符,或定义一个“[]”运算符。apidata = response[“USDBRL”];
如何在屏幕上显示数据?
2条答案
按热度按时间cgh8pdjw1#
您的问题是访问数据,要访问数据,只需使用以下命令进行访问:
出现此错误是因为您试图从响应对象本身访问
USDBRL
。从API返回的数据应该在响应对象的data
属性中。vsdwdz232#
if(apidata['error'])
这是导致错误的原因,因为apidata['error']
为null,不能用作bool并且您可以使用