json - 'Future 类型的值>' 不能分配给“列表”类型的变量'
问题描述
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>'."
我不确定为什么我要返回的 List 会发出该错误。是否有其他方法可以将 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){
})
推荐阅读
- python - 用python写游戏程序,但是程序运行时左右键没反应
- xcode - Xamarin.Froms 应用程序无法在 iPhone 上启动以进行调试
- css - 如何在 Rails 视图的表中显示来自循环的空 td 值
- python - opencv python没有足够的值来解压
- python - 结合神经网络
- mysql - 使用代理将 DataFlow 作业连接到 Cloud MySQL 是否安全(通过 os.system)
- apache - 用于 301 重定向的 Apache Cache-Control
- google-sheets - 尝试获取 Google 表格的公式
- sas - 如何平均SAS`proc报告`中的计算列
- ios - iOS:以错误的位置和大小裁剪图像