我发现了这个: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()...
因此,我在上面的第一个代码块中以冗长的方式操作了 body ,而不是像这样:
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 - Dart-如何在不同的正文中处理多个http.post请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55116371/