Home > OS >  Getting Null error while trying to display data from my api response
Getting Null error while trying to display data from my api response

Time:06-26

I am having a currency picker, which onSelect I want to fetch some records based on the selected currency and display the data in a text widget.

So my endpoint url will be like this wwww.fetchrecordbasedoncurrency?curr=${selectedCurrency}

This is the currency picker

           ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context);
                    showCurrencyPicker(
                      context: context,
                      showFlag: true,
                      showSearchField: true,
                      showCurrencyName: true,
                      showCurrencyCode: true,
                      onSelect: (Currency currency) {
                        setState(() {
                          fetchData();
                        });
                        fetchData();
                      },
                      currencyFilter: <String>[
                        'AUD',
                        'CAD',
                        'EUR',
                        'USD'
                      ],
                      favorite: ['USD'],
                    );
                  },
                  child: const Text('Select Payment Currency'),
                ),

This is the method responsible for fetching the data

 void fetchData() async {
    try {
      setState(() {
        isLoading = true;
      });
      var response = await networkHandler.get(
          networkHandler.url   'fetch-data.php?curr=${currencyType}');
      getBankInfo = BankInfo.fromJson(response);
      print("Bank Currency: ${getBankInfo.bank!.currency}");
    } catch (ex) {
      print({ex, 'An error occured while fetching bank data'});
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

It fetches the data successfully, but I get this error Null check operator used on a null value

on the widget below which is trying to display a record based on the selected currency

Text('${getBankInfo.bank!.name}')

CodePudding user response:

Hey you are getting this error in ${getBankInfo.bank!.name}. This error is because you are getting getBankInfo.bank is null and by using ! you are making it non-nullable. If you want to avoid this error then you can use ? instead of !, but by using ? if getBankInfo.bank is null then you will see null on screen. You can use null aware operator also like this getBankInfo.bank?.name ?? "".

You need to debug this line also getBankInfo = BankInfo.fromJson(response); to confirm you are getting right data or not to parse json

  • Related