【问题标题】:Http.put does not accept any but a StringHttp.put 不接受任何字符串
【发布时间】: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 模块只接受字符串,但有没有办法解决这个问题?因为它没有意义,如果我们想发布intbool<List<String>> 会发生什么。我知道您显然可以使用 .toString() 进行转换,但我的 API 有一定的验证,并且对它可以接受的内容很严格。

代码如下:

当我使用这个有效载荷时,它可以工作,因为它遵循 Http 模块的刚性类型 (<String, String>)

    Map<String, String> payloadThatWorks = {"first_name": "First Name"};

现在,当我想使用下面的代码提供Map&lt;String, List&lt;String&gt;&gt; 类型的有效负载时:

    Map<String, List<String>> payload = {
      "personal_settings": ["allow-notification-discussion-mentions"]
    };

抛出_CastError (type 'List&lt;String&gt;' 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 模块不接受任何放置&lt;String&gt; 但API 不接受除数组或&lt;List&lt;String&gt;&gt; 之外的任何内容的地方

我怎样才能绕过这个或理解为什么http put 方法如此死板?

提前谢谢你:)

山姆

【问题讨论】:

    标签: http flutter dart


    【解决方案1】:

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

    所以基本上你必须做以下事情

    String payloadStr = jsonEncode(payload)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      相关资源
      最近更新 更多