我发现了这个: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']}');
},
);
}),
);
}