我收到来自 API 的响应,但出现错误。 我在调用 topicpurchased() 时没有得到任何回应
Future<bool> topicpurchased(int topicid, String title) async {
var map = new Map<String, dynamic>();
map['topicid'] = topicid;
map['title'] = title;
var data = json.encode(map);
print(data);
var response = await http.post(Constants.ApiBaseUrl + '/topicpuchased',
headers: headers, body: data);
if (response.statusCode == 200) {
print("topicpurchasede" + response.body);
TrueOrFalse trueOrFalse = TrueOrFalse.fromJson(json.decode(response.body));
if (trueOrFalse.status == "sucess") {
print(" ????????");
return true;
} else {
print("something went wrong" + trueOrFalse.status);
return false;
}
} else {
throw Exception('Failed');
}
}
控制台报错如下
I/flutter (22130): topicpurchasede{"status":"sucess"}
I/flutter (22130): datamodel sucess
I/flutter (22130): ????????
E/flutter (22130): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Converting object to an encodable object failed: Instance of 'Future<String>'
E/flutter (22130): #0 _JsonStringifier.writeObject (dart:convert/json.dart:688:7)
E/flutter (22130): #1 _JsonStringifier.writeMap (dart:convert/json.dart:769:7)
E/flutter (22130): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:724:21)
E/flutter (22130): #3 _JsonStringifier.writeObject (dart:convert/json.dart:679:9)
E/flutter (22130): #4 _JsonStringStringifier.printOn (dart:convert/json.dart:877:17)
E/flutter (22130): #5 _JsonStringStringifier.stringify (dart:convert/json.dart:862:5)
E/flutter (22130): #6 JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter (22130): #7 JsonCodec.encode (dart:convert/json.dart:172:45)
提前致谢。
答案 0 :(得分:0)
首先,您必须使用 await 调用该函数,因为它是一个 Future:
示例:
bool response = await topicpurchased(topicid,title);
Future<bool> topicpurchased(int topicid, String title) async {
var map = new Map<String, dynamic>();
map['topicid'] = topicid;
map['title'] = title;
var data = json.encode(map);
print(data);
var response = await http.post(Constants.ApiBaseUrl + '/topicpuchased',
headers: headers, body: data);
if (response.statusCode == 200) {
print("topicpurchasede" + response.body);
//here could be the bug
TrueOrFalse trueOrFalse = TrueOrFalse.fromJson(json.decode(response.body));
if (trueOrFalse.status == "sucess") {
print(" ????????");
return true;
} else {
print("something went wrong" + trueOrFalse.status);
return false;
}
} else {
//second: here too you can send a bool return because you function has declare a
//bool response
throw Exception('Failed');
}
}
第三:错误似乎来自您的模型,您可以在此行注释并运行应用程序以查看错误是否来自那里