Home > OS >  Map List<Future<Object>> into List<Object>
Map List<Future<Object>> into List<Object>

Time:07-27

I have a

List<Future<int>> 

how do I transform it into a

List<int> 

CodePudding user response:

Credit goes to @pskink

This is how you can do it :

  List<int> resultSet = [];

  List<Future<int>> methods = [];

  resultSet = await Future.wait(methods);

You can also do it like this :

  List<int> resultSet = [];

  List<Future<int>> methods = [];

  await Future.wait(methods).then((value) {
    resultSet = value;
  });

  print(resultSet);

More about Future/wait

CodePudding user response:

If I have a hint at what you are trying to do, here is my suggestion.

  • You have a future inside a list, meaning you should await the result of the class itself before adding it to your list.
  • after doing that, you can then do something like this, to convert it to a map:
    var myMap = Map.fromIterable(myList, key: (myClassInstanceVariable) => myClassInstanceVariable.variable1, value: (myClassInstanceVariable) => myClassInstanceVariable.variable1Value);

I would have really loved it, if there was something like a more detailed explanation, so I can see how to help you with the Future. for that, I would suggest future builder

FutureBuilder<YourClass>(
    future: theAsyncMethodThatGetsYourClass,
    builder: (context, snapshot){
    //some code
    });
  • Related