【问题标题】:Dart - How to multiple http.post request with different bodiesDart - 如何对不同主体的多个 http.post 请求
【发布时间】:2019-03-12 07:43:47
【问题描述】:

我发现了这个:Optimal way to make multiple independent requests to server in Dart

但我的问题有点不同。

我想用不同的主体发布多个帖子,但我得到相同的结果,这与类型列表的最后一个元素有关。

final List<String> types = ['completed', 'approval', 'process', 'available'];

想想这个列表,我总是得到“完成”类型的结果。

Future<List<dynamic>> fetchAllRequests() async {
  int i = 0;
  userInfo['type'] = types.first;
  return Future.wait(
    types.map(
      (t) => client.post(Api.requests, body: userInfo).then(
            (response) {
              if (i < types.length - 1) {
                userInfo['type'] = types[++i];
              }
              Map<String, dynamic> m = jsonDecode(response.body);
              dataItemsLists.add(m['DataItems']);
              print('${m['DataItems']}');
            },
          ),
    ),
  );
}

另外,我想在 map() 中操纵 body 很有趣,但这不起作用:

types.map((t){client.post)(Api.requests, body: userInfo).then()...}

错误日志:

NoSuchMethodError: The method 'then' was called on null.
Receiver: null
Tried calling: then<dynamic>(Closure: (dynamic) => Null, onError: 
Closure: (dynamic, StackTrace) => Null)

在此过程中:

types.map((t) => client.post)(Api.requests, body: userInfo).then()...

所以我以详细模式操作正文,就像您在上面的第一个代码块中看到的那样,而不是像这样:

Future<List<dynamic>> fetchAllRequests() async {
  return Future.wait(
    types.map((String t) {
      userInfo['type'] = t;
      client.post(Api.requests, body: userInfo).then(
        (response) {
          Map<String, dynamic> m = jsonDecode(response.body);
          dataItemsLists.add(m['DataItems']);
          print('${m['DataItems']}');
        },
      );
    }),
  );
}

【问题讨论】:

  • types.map((t){client.post)(Api.requests, body: userInfo).then()...} 应该做什么?在client.post 之后结束) 是为了什么?

标签: dart flutter


【解决方案1】:

如果你使用{}而不是=&gt;,那么你需要显式地return

这里.map(...) 的结果是null,因为没有返回任何内容

types.map((t){client.post)(Api.requests, body: userInfo).then()...}

任意使用

types.map((t) => client.post)(Api.requests, body: userInfo).then()...;

types.map((t){return client.post)(Api.requests, body: userInfo).then()...}

在您的最后一个代码块中类似

  client.post(Api.requests, body: userInfo).then(

应该是

  return client.post(Api.requests, body: userInfo).then(

【讨论】:

  • omg,这太荒谬了,真丢脸 :),说真的我需要更多的睡眠 :) 一切都是为了回归。现在它正在工作。很抱歉给冈特带来不便,真的:)
  • :D 睡个好觉。
猜你喜欢
  • 2019-03-12
  • 1970-01-01
  • 2019-03-13
  • 1970-01-01
  • 2021-09-28
  • 2010-12-28
  • 2021-08-12
  • 2014-01-25
  • 1970-01-01
相关资源
最近更新 更多