首页 > 解决方案 > 如何使用颤振发布字符串和列表的映射

问题描述

我正在尝试发送一个字符串和列表的映射,如下所示:

Map<String, List<int>> results = {
  "tags": [5 , 10]
}
  Object headers = {
    HttpHeaders.authorizationHeader: "Bearer ${accessToken}",
    "Accept": "application/json",
  };

我这样发布:

  post() {
    return http
        .post("$resource/$baseName/$id$query",
            headers: headers,
            body: results ,
            )
        .then((http.Response response) {
        return json.decode(response.body);
    }).catchError((err) {
      print(err);
    });
  }

我得到了这个错误:

type 'List<int>' is not a subtype of type 'String' in type cast

我也想我应该发送

Map<String,String>

但是我有

Map<String, List<int>>

我尝试了很多东西,但对颤动也很陌生,所以我很困惑,如果有人可以帮助我,谢谢。编辑:

我试试 dio

try {
      Response response =
          await Dio().post("$resource/$baseName/$id$query", data: {
        'tags': [1, 2]
      },
      options: Options(headers: headers)
      );
      print(response);
    } catch (e) {
      print(e);
    }

标签: flutterdart

解决方案


发送数据时是否对数据进行编码?在发送之前尝试对数据进行编码。您指定您的标头接受 application/json,但您可能不会发送 json。

见:https ://api.dartlang.org/stable/2.5.0/dart-convert/jsonEncode.html

import 'dart:convert';

 Map<String, List<int>> results = {
  "tags": [5 , 10]
};

  final encodedResults = jsonEncode(results); // send these encoded results.

推荐阅读