I have a connection with API, and it is working with no problem in postman: like this:
but I have a problem with flutter: this is the code :
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;
}
the returned status code is
(200)
but return null, and show me this message:
I/flutter (10607): status code 200
I/flutter (10607): msg error : type 'Null' is not a subtype of type 'Map<String, dynamic>'
and this is the model:
// 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,
};
}
CodePudding user response:
You are getting this error because there is only data
field in json.decode(str)
. You write to return null in your code if any field is null.