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?

huangapple go评论55阅读模式
英文:

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?

问题

以下是翻译的部分:

  1. 在我的Flutter应用程序中,我尝试在initState中调用API,并且成功地以我想要的格式获取了响应。我知道这一点,因为当我尝试在按钮按下时打印变量时,我得到了正确的响应。但是,当我尝试在实际应用程序中显示这个响应,比如通过文本小部件或ListView时,出现了错误。

  2. 我做了以下操作:

    1. 在initState方法中调用了我的API,并且成功地获取了响应:
    dynamic myArticles = {};
    
    @override
    void initState() {
        super.initState();
        getTopNews().then((value) {
          setState(() {
          myArticles = value;
        });
      });
    }
    
    1. 我有一个按钮,成功显示了我从API中想要的响应:
    MaterialButton(
       child: Text("点击"),
       onPressed: () {
         print(myArticles["articles"][0]["description"]);
       }
    )
    //点击按钮后,按钮会打印出我想要的值。
    
    1. 我添加了一个文本小部件的代码,它应该显示信息,然后重新加载了应用程序,但出现了错误。
    Text(myArticles["articles"][0]["description"])
    // 这行代码返回一个错误。
    

    步骤3中的错误信息如下:

    (NoSuchMethodError: 调用了null上的方法'[]'。
    接收者:null
    尝试调用:[](0))
    

为什么我会收到这个错误,我如何解决它?我知道我正确地调用了API,我得到了正确的数据,但当我尝试在应用程序中显示相同的信息时,我会收到错误。

英文:

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.

答案1

得分: 0

因为在第一次构建时,myArticles 是空的,而 myArticles["articles"] 会为 null。

你可以使用 ? 来修复它:

Text(myArticles["articles"]?[0]["description"] ?? "")
英文:

Because at the first time build, myArticles is empty and myArticles["articles"] will be null.

You can fix it with ? :

Text(myArticles["articles"]?[0]["description"] ?? "") 

答案2

得分: 0

你可以在执行onPress后调用你的API并重新渲染你的小部件树。这将有助于获取响应并更新用户界面。

MaterialButton(
   child: Text("点击"),
   onPressed: () {
     getTopNews().then((value) {
      setState(() {
      myArticles = value;
    });
   }
)
英文:

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

huangapple
  • 本文由 发表于 2023年2月24日 15:26:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定