Book Image

Mastering Dart

By : Sergey Akopkokhyants
Book Image

Mastering Dart

By: Sergey Akopkokhyants

Overview of this book

Table of Contents (19 chapters)
Mastering Dart
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 can be very useful. On one hand, we can give Future to any number of consumers to observe the resolution independently; on the other hand, Completer can be given to any number of producers and Future will be resolved...