Http.put只接受字符串

时间:2019-08-08 08:04:49

标签: http flutter dart

很简单,我正在尝试向我的API发出PUT请求,但出现类型错误:

_CastError (type 'List<String>' is not a subtype of type 'String' in type cast)

我的API接受字符串(string[])的数组,因为我当前正在同级Web平台上使用它,所以我知道它可以工作。因此,我尝试使用以下代码在Flutter应用上复制该代码。目前,这只是静态代码。

我知道,http模块仅接受字符串,但是有办法解决吗?因为这没有意义,所以如果我们要发布intbool<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;
    }

但是,在我的窗口小部件中调用辅助函数时...

http.Response response =
        await ApiService.queryPut('/api/users/$username', body: payload);

因此,我处于http模块不接受放置<String>的任何东西,但API除了数组或<List<String>>之外不接受任何东西的地方

如何解决这个问题或了解http放置方法为何如此严格?

预先感谢您:)

山姆

1 个答案:

答案 0 :(得分:0)

您可以导入dart:convert并使用其jsonEncode将您的地图或地图数组转换为字符串

因此,基本上,您将必须执行以下操作

String payloadStr = jsonEncode(payload)

并使用此payloadStr传递http方法。同样,您可以使用JsonDecoder将json字符串转换为Map或map的数组。