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:
- 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;
});
});
}
- 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.
- 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.