O'Reilly logo

Mastering Dart by Sergey Akopkokhyants

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Future

Let's change the code from the previous section into async, as follows:

import 'dart:io';

main() {
  File file = new File("data.txt");
  file.open().then(processFile);
}

processFile(RandomAccessFile file) {
  file.length().then((int length) {
    file.read(length).then(readFile).whenComplete(() {
      file.close();
    });
  });
  }

readFile(List<int> content) {
  String contentAsString = new String.fromCharCodes(content);
  print("Content:  $contentAsString");
}

As you can see, the Future class is a proxy for an initially unknown result and returns a value instead of calling a callback function. Future can be created by itself or with Completer. Different ways of creating Future must be used in different cases. The separation of concerns between Future and Completer ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required