簡體   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