Extending Future

627 Views Asked by At

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> {

2

There are 2 best solutions below

1
On BEST ANSWER

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;
}
1
On

Instead of trying to extend a future, you just need to 'use' the future.

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 {
  Future<String> letsWait => new Future<String>(_letsWait);

  String _letsWait() {
    for (var i = 0; i < 5000000000; i++) {
      // lol
    }
    return 'finally';
  }
}

Generally a future can be constructed without using a completer except in certain circumstances. The default constructor for Future will automatically wrap your passed function (which takes no arguments) in a Timer.run() to perform it asynchronously.