2

I found this: Optimal way to make multiple independent requests to server in Dart

But my issue is a bit different.

I want to make multiple posts with different bodies but I get the same results, which is related to the last element of types list.

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

Think about this list, I'm always getting 'completed' type results.

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

Also, I want to manipulate the body inside the map() fun, but this is not working:

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

Error log:

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

While this is working:

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

So I manipulate in a verbose mode the body as you see in my first code block up above instead of like this way:

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']}');
        },
      );
    }),
  );
}
Mehmet Esen
  • 6,156
  • 3
  • 25
  • 44
  • What is `types.map((t){client.post)(Api.requests, body: userInfo).then()...}` supposed to do? What is the closing `)` after `client.post` for? – Günter Zöchbauer Mar 12 '19 at 08:22

1 Answers1

3

If you use {} instead of =>, then you need to explicitly return

Here the result of .map(...) is null because nothing is returned

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

Either use

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

or

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

Similar in your last code block

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

should be

  return client.post(Api.requests, body: userInfo).then(
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567