flutter - 未处理的异常:键入“列表”'不是类型转换颤振http post请求中'String'类型的子类型
问题描述
我正在尝试使用包含对象数组的字段的颤振发送发布请求,我应该发送一个包含对象的 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.
解决方案
您可以在 JSON 中编码您的 POST 正文。
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
推荐阅读
- python - 编辑图像 Python 的元数据
- javascript - 滚动到顶部时如何将导航背景颜色更改为透明?
- mysql - 显式事务和隐式事务是什么意思并举例说明
- angular - 在 Angular 中的事件前面添加“$”美元符号有什么影响?
- javascript - 如何将json数组中的`pid`转换为`children`形式的数组?
- android - 整个 res 文件夹不会从 Android Studio Project 推送到 github
- python - 删除两个数组中的匹配元素 - Python
- latex - 如何在 pgfplots 中绘制平滑曲线?以及如何删除 y 轴刻度?
- python - conda、yarn、npm 的 SSL 证书已损坏,但 pip 有效
- javascript - 如何编写存储信息并显示信息的投票栏?