Flutter获取API

vjrehmav  于 2022-12-05  发布在  Flutter
关注(0)|答案(2)|浏览(140)

我试图从外部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”];

如何在屏幕上显示数据?

cgh8pdjw

cgh8pdjw1#

您的问题是访问数据,要访问数据,只需使用以下命令进行访问:

response.data['USDBRL']

出现此错误是因为您试图从响应对象本身访问USDBRL。从API返回的数据应该在响应对象的data属性中。

vsdwdz23

vsdwdz232#

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

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

并且您可以使用

apidata['USDBRL']

相关问题