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:
dynamic myArticles = {};
@override
void initState() {
super.initState();
getTopNews().then((value) {
setState(() {
myArticles = value;
});
});
}
MaterialButton(
child: Text("Click"),
onPressed: () {
print(myArticles["articles"][0]["description"]);
}
)
//On clicked, the button prints out the value I want.
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.
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;
});
}
)