Search code examples
flutterdartflutter-http

Why can I use print my API response on a button press but not display it as a widget in Flutter? And how do I fix it?


In my Flutter App, I am trying to call an API in initState and I am able to successfully get a response in the format that I want. I know this because when I try and print the variable on a button press, I get the correct response. However, when I try to display this response in the actual app such as through a text widget or a ListView, I get an error.

Here is what I did:

  1. I called my API in the initState method and I was able to successfully get my response:
dynamic myArticles = {};
  
@override
void initState() {
    super.initState();
    getTopNews().then((value) {
      setState(() {
      myArticles = value;
    });
  });
}
  1. I have a button that successfully displays the response that I want from the API:
MaterialButton(
   child: Text("Click"),
   onPressed: () {
     print(myArticles["articles"][0]["description"]);
   }
)
//On clicked, the button prints out the value I want. 
  1. I added the code for a Text widget that is supposed to display the information, and I reloaded the app, but I get an error.
Text(myArticles["articles"][0]["description"]) 
// This line of code returns an error. 

The error that I get from step 3 says this:

(NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: [](0))

Why am I getting this error and how can I solve it? I know that I am calling the API correctly and I am getting the correct data back, yet when I try to display the same information in the app I am getting an error.


Solution

  • One thing you can do is once you do onPress you can call your API and re-render your widget tree. This will help you to get response and update the UI.

    MaterialButton(
       child: Text("Click"),
       onPressed: () {
         getTopNews().then((value) {
          setState(() {
          myArticles = value;
        });
       }
    )