繁体   English   中英

如何在颤动中将文件对象转换为可编码的 json 对象?

[英]How to convert file object to encodable json object in flutter?

我正在尝试使用 dart 将 profilePicture 映射到 File 对象,我在 c# 后端将 profilePicture 保存为 IFormFile ..

这是我的 ManageUserModel 类中的映射函数和其他函数:

Map<String, dynamic>toMap() {
return { 
"profilePicture":profilePicture,
(other mappings)
}
}
List<ManageUserModel> fromJson(String jsonData) {
 // Decode json to extract a map
final data = json.decode(jsonData);
return List<ManageUserModel>.from(
  data.map((item) => ManageUserModel.fromJson(item)));
 }

String toJson(ManageUserModel data) {
// First we convert the object to a map
final jsonData = data.toMap();
// Then we encode the map as a JSON string
 return json.encode(jsonData);
 }

请注意, profilePicture 是 ManageUserModel 属性之一,属于File类型。

当通过此方法调用 http 更新请求时:

 Future<String> updateUser(ManageUserModel data) async {
 final response = await client.put("$baseUrl/Users",
  headers: {"content-type": "application/json"},
  body: toJson(data),
  );
  if (response.statusCode == 200) {
  return "Success";
  } else {
  return "Fail";
  }
  }

我收到此错误:

E/flutter (10061): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] 未处理异常:将对象转换为可编码对象失败:“_File”实例

有什么帮助吗?

从您提供的错误来看,您似乎正在尝试将“_File”对象映射为 json。

E/flutter (10061): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Converting object to an encodable object failed: Instance of '_File'

那是行不通的,因为fromJson只能处理Maps 您可能要考虑的是将文件存储为图像 URL,或者之前在评论中提到的内容 - 作为 base64。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM