如何解决未处理的异常:类型 'List<int>' 不是类型转换 Flutter http post 请求中类型 'String' 的子类型
我正在尝试使用包含对象数组的字段的 Flutter 发送 post 请求,我应该发送一个包含对象的 int (ids) 的列表.. 类似
List<int> theList = [10,20,30,40,50]
Unhandled Exception: type 'List<int>' is not a subtype of type 'String' in type cast Flutter HTTP post request
这是我的代码:
Future lawyerRegister(LawyerRegisterModel lawyerRegisterModel) async {
String theUrl = '${baseURL}Lawyer/';
Client client = Client();
List<int> lawyerIDImageBytes =
await File(lawyerRegisterModel.lawyerIDImagePath).readAsBytes();
String lawyerIDImageBytes64Image = base64Encode(lawyerIDImageBytes);
List<int> personalImageBytes =
await File(lawyerRegisterModel.lawyerIDImagePath).readAsBytes();
String personalImageBytes64Image = base64Encode(personalImageBytes);
try {
return client.post(theUrl,headers: {
'Authorization': 'Token $thetoken',},body: {
'sections': lawyerRegisterModel.fields,//Error comes from this line,here is where i want to send the array of objects
'city': lawyerRegisterModel.cityID.toString(),'bio': lawyerRegisterModel.bio,'full_name': lawyerRegisterModel.fullName,'mobile': lawyerRegisterModel.mobile,'lawyer_id': lawyerIDImageBytes64Image,'image': personalImageBytes64Image,}).then((response) {
print(response.body);
});
} catch (e) {
print(e);
} finally {
client.close();
}
}
当我尝试更改字段以将其作为字符串发送时
'sections': lawyerRegisterModel.fields.toString(),
它从后端返回此错误:
Incorrect type. Expected pk value,received str.
解决方法
您可以将 POST 正文编码为 JSON。
return client.post(theUrl,headers: {
'Authorization': 'Token $theToken',},body: jsonEncode({
'sections': lawyerRegisterModel.fields,'city': lawyerRegisterModel.cityID.toString(),'bio': lawyerRegisterModel.bio,'full_name': lawyerRegisterModel.fullName,'mobile': lawyerRegisterModel.mobile,'lawyer_id': lawyerIDImageBytes64Image,'image': personalImageBytes64Image,}))
编辑:请注意您需要为 import 'dart:convert'
设置 jsonEncode
您可以将 int 列表编码为字符串
import 'dart:convert';
List<int> theList = [10,20,30,40,50];
String encodedList = jsonEncode(theList);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。