gpt4 book ai didi

json - 类型 'Future>' 的值不能分配给类型 'List' 的变量

转载 作者:行者123 更新时间:2023-12-03 03:23:37 28 4
gpt4 key购买 nike

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

String opentdb = 'https://opentdb.com/api.php?amount=15&type=boolean';

class QuestionServices {
Future<List<Question>> getData() async {
List<Question> questions;
String link = opentdb;
var res = await http
.get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
print(res.body);
if (res.statusCode == 200) {
var data = json.decode(res.body);
var rest = data['results'] as List;
print(rest);
questions =
rest.map<Question>((json) => Question.fromJson(json)).toList();
}
print("List Size: ${questions.length}");
// _questions = questions;
return questions;
}

List<Question> newQuestions = getData();
}
class Question {
final String question;
final bool answer;

Question({this.question, this.answer});

factory Question.fromJson(Map<String, dynamic> json) {
return Question(
question: json['question'] as String,
answer: json['correct_answer'] as bool,
);
}
}

我正在尝试从 JSON 数据库创建问题列表,但每当我尝试获取返回的列表时,我都会收到错误消息:

"A value of type 'Future<List<Question>>' can't be assigned to a variable of type 'List<Question>'."

我不确定为什么我返回的列表会发出该错误。是否有其他方法可以将 json 添加到列表中?

最佳答案

List<Question> getData() async { // remove Future
List<Question> questions;
String link = opentdb;
...


//how to access now you will get instance of List<Question>

getData().then((List<Question> newQuestions){

})

关于json - 类型 'Future<List<Question>>' 的值不能分配给类型 'List<Question>' 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60262715/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com