Dart - 如何使用不同的主体进行多个 http.post 请求

标签 dart flutter

我发现了这个: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() 函数中操作主体,但这不起作用:

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']}');
        },
      );
    }),
  );
}

最佳答案

如果您使用 {} 而不是 =>,那么您需要显式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(

关于Dart - 如何使用不同的主体进行多个 http.post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55116371/

相关文章:

Flutter - 在 pubspec.yaml 中添加 pub 包

当第二个屏幕上没有交互时,Flutter 导航回主屏幕

android - flutter ,云火存储查询方法,其中无法正常工作

dart - 升级后的 dart,现在在我的 Web UI 自动生成代码中出现 noSuchMethod 异常

flutter - 在运行默认应用程序时,Flutter 在切换到 Master 后抛出“日志阅读器意外停止”

git - 如何在 Flutter 和 Android Studio 中使用 git?

dart - 如何在 Flutter 中从 Canvas 中获取 PNG 图片数据?

dart - 我可以将 MediaQuery.of(context) 固定为常数值吗?

gridview - 如何在 Flutter 的 GridView 中为 Widget 设置自定义高度?

dart - 滚动 Controller 未附加到任何 ScrollView