首页 > 解决方案 > Flutter - 向我的服务器发出 HTTP 发布请求时出错

问题描述

所以我有这个 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]

标签: httpdartflutter

解决方案


bodyofhttp.post只能是以下之一:

  1. 一个字节数组作为List<int>
  2. 一个字符串,将通过 UTF-8 编码将其转换为字节数组
  3. AMap<String, String>将被编码为 HTML 表单数据,即 x-www-form-urlencoded

您正在传递 a Map<String, List<String>>,这不是上述内容。你的服务器需要什么?也许是一个 json 编码的字符串?(如果是这样,请使用json.encode(data)。)


推荐阅读