我有一个与API的连接,它是工作与没有问题的 Postman :例如:
但我对Flutter有个问题:下面是代码:
Future<List<AnswerData>> searchAnswers({required String search}) async {
final response = await post(
Uri.parse("$_url/search"),
headers: <String, String>{
'Content-Type': "application/json",
'Connection' : 'keep-alive',
'Accept' : '*/*',
},
body: jsonEncode(<String, String>{"search" : "oop"})
);
print("status code${response.statusCode}");
final answers = answerFromJson(response.body);
print("msg error ${answers.data}");
return answers.data;
}
返回的状态代码为
(200)
但返回null,并显示以下消息:
I/flutter (10607): status code 200
I/flutter (10607): msg error : type 'Null' is not a subtype of type 'Map<String, dynamic>'
这就是模型:
// To parse this JSON data, do
//
// final answer = answerFromJson(jsonString);
import 'dart:convert';
import 'dart:io';
Answer answerFromJson(String str) => Answer.fromJson(json.decode(str));
String answerToJson(Answer data) => json.encode(data.toJson());
class Answer {
Answer({
required this.data,
required this.links,
});
List<AnswerData> data;
Links links;
factory Answer.fromJson(Map<String, dynamic> json) => Answer(
data: List<AnswerData>.from(json["data"].map((x) => AnswerData.fromJson(x))),
links: Links.fromJson(json["links"]),
);
Map<String, dynamic> toJson() => {
"data": data == null ? null : List<dynamic>.from(data.map((x) => x.toJson())),
"links": links == null ? null : links.toJson(),
};
}
class AnswerData {
AnswerData({
required this.title,
required this.text,
required this.link,
required this.course,
});
String title;
String text;
String link;
String course;
factory AnswerData.fromJson(Map<String, dynamic> json) => AnswerData(
title: json["title"] == null ? null : json["title"],
text: json["text"] == null ? null : json["text"],
link: json["link"] == null ? null : json["link"],
course: json["course"] == null ? null : json["course"],
);
Map<String, dynamic> toJson() => {
"title": title == null ? null : title,
"text": text == null ? null : text,
"link": link == null ? null : link,
"course": course == null ? null : course,
};
}
class Links {
Links({
required this.first,
required this.last,
this.prev,
this.next,
});
String first;
String last;
dynamic prev;
dynamic next;
factory Links.fromJson(Map<String, dynamic> json) => Links(
first: json["first"] == null ? null : json["first"],
last: json["last"] == null ? null : json["last"],
prev: json["prev"],
next: json["next"],
);
Map<String, dynamic> toJson() => {
"first": first == null ? null : first,
"last": last == null ? null : last,
"prev": prev,
"next": next,
};
}
1条答案
按热度按时间2uluyalo1#
出现此错误是因为
json.decode(str)
中只有data
字段。如果任何字段为空,则在代码中写入以返回空值。