所以我有这个Future函数,用于向服务器发出HTTP请求:
Future getReviewsComments(List reviewIDs) async {
Map data = {
"reviewIDs": [reviewIDs]
};
http.Response response = await http.post(
Uri.encodeFull(config.domain + '/getReviewsComments'),
body: data
);
if (response.statusCode != 200){
return false;
}
return json.decode(response.body);
}
该函数在我的initState
函数中运行,例如:
void initState(){
List reviewIDs = ["5c4962b37d6b5f50146b8df9", "5c4966901bd9c3141c2f4700"];
eventActions.getReviewsComments(reviewIDs).then(
(comments){
print( "WORKDED");
}
);
super.initState();
}
但是当我运行该应用程序时,出现此错误:
E/flutter ( 7567): [ERROR:flutter/shell/common/shell.cc(186)] Dart Error: Unhandled exception:
E/flutter ( 7567): type 'List<dynamic>' is not a subtype of type 'String' in type cast
E/flutter ( 7567): #0 CastMap.forEach.<anonymous closure> (dart:_internal/cast.dart:286:25)
E/flutter ( 7567): #1 __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.forEach (dart:collection/runtime/libcompact_hash.dart:367:8)
E/flutter ( 7567): #2 CastMap.forEach (dart:_internal/cast.dart:285:13)
E/flutter ( 7567): #3 mapToQuery
package:http/src/utils.dart:17
E/flutter ( 7567): #4 Request.bodyFields=
...
请如何解决?
注意:print(reviewIDs)
返回[5c4962b37d6b5f50146b8df9, 5c4966901bd9c3141c2f4700]
答案 0 :(得分:1)
body
中的http.post
只能是以下之一:
List<int>
Map<String, String>
,它将被编码为HTML表单数据,即x-www-form-urlencoded 您正在传递Map<String, List<String>>
,以上都不是。您的服务器需要什么?也许是JSON编码的字符串? (如果是这样,请使用json.encode(data)
。)
答案 1 :(得分:0)
尝试从Future函数返回响应并将响应放入列表中。
示例:
Future<http.Response> getReviewsComments(List reviewIDs) async {
Map data = {
"reviewIDs": [reviewIDs]
};
http.Response response = await http.post(
Uri.encodeFull(config.domain + '/getReviewsComments'),
body: json.encode(data)
);
return response;
}
然后在您的initState
函数中从服务器提取该响应
void initState(){
List reviewIDs = ["5c4962b37d6b5f50146b8df9", "5c4966901bd9c3141c2f4700"];
eventActions.getReviewsComments(reviewIDs).then(
(response){
print('Response from server is: ${response.body}');
}
);
super.initState();
}