Page 13 - Dart Language
P. 13

Chapter 2: Asynchronous Programming




        Examples



        Returning a Future using a Completer


         Future<Results> costlyQuery() {
           var completer = new Completer();

           database.query("SELECT * FROM giant_table", (results) {
             // when complete
             completer.complete(results);
           }, (error) {
             completer.completeException(error);
           });

           // this returns essentially immediately,
           // before query is finished
           return completer.future;
         }


        Async and Await



         import 'dart:async';

         Future main() async {
           var value = await _waitForValue();
           print("Here is the value: $value");
           //since _waitForValue() returns immediately if you un it without await you won't get the
         result
           var errorValue = "not finished yet";
           _waitForValue();
           print("Here is the error value: $value");// not finished yet
         }

         Future<int> _waitForValue() => new Future((){

           var n = 100000000;

           // Do some long process
           for (var i = 1; i <= n; i++) {
             // Print out progress:
             if ([n / 2, n / 4, n / 10, n / 20].contains(i)) {
               print("Not done yet...");
             }

             // Return value when done.
             if (i == n) {
               print("Done.");
               return i;
             }
           }
         });






        https://riptutorial.com/                                                                                8
   8   9   10   11   12   13   14   15   16   17   18