首页 > 解决方案 > 未处理的异常:键入“列表”'不是类型转换颤振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.

标签: flutterhttpdartpost

解决方案


您可以在 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


推荐阅读