Search code examples
dartextendsdart-async

Extending Future


I find quite a lot about using but not about defining futures in Dart. Lets say I have letsWait() which takes quite some time. How do I use the Future class?

import 'dart:async';

void main() {
  print('Let\'s get started');
  ArtificialWait waitPoint = new ArtificialWait();
  Future<String> future = waitPoint.letsWait();
  // and how about printing the return here?
  print('something fast');
}

class ArtificialWait extends Future<String> {
  String letsWait() {
    for (var i = 0; i < 5000000000; i++) {
      // lol
    }
    return 'finally';
  }
}

This try gives me a:

unresolved implicit call to super constructor 'Future()' class ArtificialWait extends Future<String> {


Solution

  • I don't know why you want to inherit from Future. Normally you would use this like:

    import 'dart:async';
    
    void main() {
      print('Let\'s get started');
      artificialWait().then((e) => print(e));
      // and how about printing the return here?
      print('something fast');
    }
    
    Future<String> artificialWait  () {
      var completer = new Completer<String>();
      Timer.run(() {
        for (var i = 0; i < 5000000000; i++) {
          // lol
        }
        completer.complete('finally');
      });
      return completer.future;
    }