Использование async / wait в dart не ждет с пакетом http - PullRequest
0 голосов
/ 20 апреля 2020

Я прочитал предыдущие вопросы, связанные с этой топикой c, но не смог понять, что происходит. Я думаю, что я сделал точно такой же процесс, описанный в этом официальном видео дартс / флаттер - https://www.youtube.com/watch?v=SmTCmDMi4BY

То, что я пытаюсь сделать, очень просто. Я хочу сделать вызов API и мне нужно дождаться ответа. но я не вижу, как это работает. Может быть, мое понимание async / wait неверно. Если я проверяю вывод консоли, я получаю вот так

Staring the Program
Ending the Program
Got the questions list
[Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question']

Может кто-нибудь помочь мне с этим.

import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  print('Staring the Program');
  getQuestions();
  print('Ending the Program');
}

void getQuestions() async {
  QuizModel qm = QuizModel();
  List<Question> questionsList = await qm.getQuestions();
  print('Got the questions list');
  print(questionsList);
}

class Question {
  String question;
  bool answer;
  Question({this.question, this.answer});
}

class QuizModel {
  var quizData;

  Future<List<Question>> getQuestions() async {
    NetworkHelper networkHelper =
        NetworkHelper('https://opentdb.com/api.php?amount=10&type=boolean');
    quizData = await networkHelper.getData();
    final List<Question> questionsList = [];
    for (final question in quizData['results']) {
      bool answer;
      question['correct_answer'] == 'True' ? answer = true : answer = false;
      questionsList
          .add(Question(question: question['question'], answer: answer));
    }
    return questionsList;
  }
}

class NetworkHelper {
  final String _url;
  NetworkHelper(this._url);

  Future<dynamic> getData() async {
    http.Response response = await http.get(_url);

    if (response.statusCode == 200) {
      var jsonData = jsonDecode(response.body);
      return jsonData;
    } else {
      print(response.statusCode);
    }
  }
}

Ответы [ 3 ]

1 голос
/ 20 апреля 2020

QuizModel.getQestions() - это будущее.

Ваша программа печатает начало, вызов будущего и окончание печати. Он не ждет будущего, getQuestions.

Вы можете добавить asyn c к своему основному и ожидать вызова метода.

0 голосов
/ 20 апреля 2020
I/flutter (18222): Staring the Program
I/flutter (18222): Got the questions list
I/flutter (18222): [Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question', Instance of 'Question']
I/flutter (18222): Ending the Program

если вам нужно получить этот отпечаток, вы должны заменить

void main() {
  print('Staring the Program');
  getQuestions();
  print('Ending the Program');
}

void getQuestions() async {
  QuizModel qm = QuizModel();
  List<Question> questionsList = await qm.getQuestions();
  print('Got the questions list');
  print(questionsList);
}

на

void main()async {
  print('Staring the Program');
  await getQuestions();
  print('Ending the Program');
}

Future<void> getQuestions() async {
  QuizModel qm = QuizModel();
  List<Question> questionsList = await qm.getQuestions();
  print('Got the questions list');
  print(questionsList);
}
0 голосов
/ 20 апреля 2020

вы печатаете экземпляр списка вопросов. если вы хотите распечатать вопросы вопросов, вам нужно сделать это

void getQuestions() async {
  QuizModel qm = QuizModel();
  List<Question> questionsList = await qm.getQuestions();
  print('Got the questions list');
  for(final question in questionsList){
    print(question.question);
  }
}

вместо

void getQuestions() async {
  QuizModel qm = QuizModel();
  List<Question> questionsList = await qm.getQuestions();
  print('Got the questions list');
  print(questionsList);
}
...