【问题标题】:Flutter http.get not executing颤振http.get没有执行
【发布时间】:2020-11-25 10:45:33
【问题描述】:

我对@9​​87654322@ 很陌生,遇到了以下问题:

  child: RaisedButton(
   onPressed: () {
   fetchData();
  },
  // ...
  fetchData() async {
    final res = await http.get("https://jsonplaceholder.typicode.com/posts");
    if (res.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      print("it works");
      return json.decode(res.body);
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }
  // ...

当我删除 http.get 部分时,它会打印“它可以工作”,所以我认为问题出在 http.get 执行中。

【问题讨论】:

  • 需要更多解释,它会抛出错误Failed to load post??
  • 不,没有什么事情发生
  • 尝试 curl 或 postman 获取相同的 url,发布结果
  • 邮递员的邮件标题详细信息

标签: http flutter dart


【解决方案1】:

使 onPressed async 并将 await 添加到 fetchData()。

【讨论】:

    【解决方案2】:

    让你的方法类型为Future,并让它像这样返回数据类型dynamic。然后在任何你想调用的地方调用它。

      Future<dynamic> fetchData() async {
        final res = await http.get("https://jsonplaceholder.typicode.com/posts");
        if (res.statusCode == 200) {
          // If the call to the server was successful, parse the JSON
          print("it works");
          return json.decode(res.body);
        } else {
          // If that call was not successful, throw an error.
          throw Exception('Failed to load post');
        }
      }
    

    并通过 this 调用它,因为您正在返回数据

         child: RaisedButton(
          onPressed: () {
            // the value is the call back function data which you're returning 
            fetchData().then((value){
                 // since the data it return is a dynamic one
                 print(value.toString());
            });
          }
         )
    

    如果您不想返回任何数据,只需调用该方法即可。然后这样做

      fetchData() async {
        final res = await http.get("https://jsonplaceholder.typicode.com/posts");
        if (res.statusCode == 200) {
          // If the call to the server was successful, parse the JSON
          print("it works");
          // do not return
          print(json.decode(res.body).toString());
        } else {
          // If that call was not successful, throw an error.
          throw Exception('Failed to load post');
        }
      }
    

    并且只需像在代码中调用方法一样调用

        child: RaisedButton(
          // no need of anything now
          onPressed: () => fetchData()
         )
    

    【讨论】:

      【解决方案3】:

      运行Flutter clean解决了还是不知道怎么解决

      【讨论】:

        猜你喜欢
        • 2021-10-12
        • 2019-03-30
        • 2021-12-18
        • 1970-01-01
        • 2021-09-03
        • 2019-08-01
        • 1970-01-01
        • 2019-02-26
        • 1970-01-01
        相关资源
        最近更新 更多