【发布时间】:2019-08-08 08:04:49
【问题描述】:
很简单,我正在尝试向我的 API 发出 PUT 请求,但我收到以下类型错误:
_CastError (type 'List<String>' is not a subtype of type 'String' in type cast)
我的 API 接受一个字符串数组 (string[]),我知道它可以工作,因为我目前正在兄弟网络平台上使用它。所以我试图用下面的代码在 Flutter 应用程序上复制它。目前只是静态代码。
我知道,http 模块只接受字符串,但有没有办法解决这个问题?因为它没有意义,如果我们想发布int、bool 或 <List<String>> 会发生什么。我知道您显然可以使用 .toString() 进行转换,但我的 API 有一定的验证,并且对它可以接受的内容很严格。
代码如下:
当我使用这个有效载荷时,它可以工作,因为它遵循 Http 模块的刚性类型 (<String, String>)
Map<String, String> payloadThatWorks = {"first_name": "First Name"};
现在,当我想使用下面的代码提供Map<String, List<String>> 类型的有效负载时:
Map<String, List<String>> payload = {
"personal_settings": ["allow-notification-discussion-mentions"]
};
抛出_CastError (type 'List<String>' is not a subtype of type 'String' in type cast)的错误
在下面的http.put函数中:
主要 API 帮助函数
static Future<http.Response> queryPut(String apiPath, {dynamic body}) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String accessToken = prefs.getString('access_token');
var response = await http.put(
Uri.encodeFull(_urlBase + '$apiPath'),
body: body,
headers: {
HttpHeaders.authorizationHeader: "Bearer $accessToken",
'Accept': 'application/json'
},
);
return response;
}
但是,当在我的 Widget 中调用辅助函数时...
http.Response response =
await ApiService.queryPut('/api/users/$username', body: payload);
所以我处于http 模块不接受任何放置<String> 但API 不接受除数组或<List<String>> 之外的任何内容的地方
我怎样才能绕过这个或理解为什么http put 方法如此死板?
提前谢谢你:)
山姆
【问题讨论】: