skip to Main Content

Im trying to fetch data from external api, but my screen show this error message:

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

My Screen code is this:

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(),
            )
        )
    );
  }
}

My print message show the data from 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"}}

I tried to access data as ‘apidata = response["USDBRL"]’ but it show error: lib/screens/prices.dart:27:23: Error: The operator ‘[]’ isn’t defined for the class ‘Response’.

  • ‘Response’ is from ‘package:dio/src/response.dart’ (‘../../snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/dio-4.0.6/lib/src/response.dart’).
    Try correcting the operator to an existing operator, or defining a ‘[]’ operator.
    apidata = response["USDBRL"];

How can i show the data in screen?

2

Answers


  1. Your problem is accessing the data, to do that, simply access using:

    response.data['USDBRL']
    

    You got the error because you are trying to access the USDBRL from the response object itself. The data returned from the api should be inside the data attribute of the response object.

    Login or Signup to reply.
  2. if(apidata['error']) this is causing the error becsuse apidata['error'] is null and can’t be used as bool

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

    and you can access data with

     apidata['USDBRL']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search