微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

未处理的异常:类型 'List<int>' 不是类型转换 Flutter http post 请求中类型 'String' 的子类型

如何解决未处理的异常:类型 'List<int>' 不是类型转换 Flutter http post 请求中类型 'String' 的子类型

我正在尝试使用包含对象数组的字段的 Flutter 发送 post 请求,我应该发送一个包含对象的 int (ids) 的列表.. 类似

List<int> theList = [10,20,30,40,50]

但是Flutter不会让我以这种方式发送它返回错误

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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?