Flutter http.get не выполняется - PullRequest
1 голос
/ 05 августа 2020

Я новичок в Flutter и застрял на следующей проблеме:

  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 выполняется.

Ответы [ 3 ]

0 голосов
/ 06 августа 2020

Сделайте ваш метод типа 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');
    }
  }

И вызывайте его через это, поскольку вы возвращаете данные

     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()
     )
0 голосов
/ 06 августа 2020

Решено, запустив Flutter clean, еще не знаю как

0 голосов
/ 05 августа 2020

Сделайте onPressed asyn c и добавьте await в fetchData ().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...