Dart, how to create a future to return in your own functions?

If you need to create a future, you can use a Completer. See Completer class in the docs. Here is an example:

Future<List<Base>> GetItemList(){
  var completer = new Completer<List<Base>>();
    
  // At some time you need to complete the future:
  completer.complete(new List<Base>());
    
  return completer.future;
}

But most of the time you don’t need to create a future with a completer. Like in this case:

Future<List<Base>> GetItemList(){
  var completer = new Completer();
    
  aFuture.then((a) {
    // At some time you need to complete the future:
    completer.complete(a);
  });
    
  return completer.future;
}

The code can become very complicated using completers. You can simply use the following instead, because then() returns a Future, too:

Future<List<Base>> GetItemList(){
  return aFuture.then((a) {
    // Do something..
  });
}

Or an example for file io:

Future<List<String>> readCommaSeperatedList(file){
  return file.readAsString().then((text) => text.split(','));
}

See this blog post for more tips.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)