How to timeout a future computation after a timeLimit?

Future.await[_doSome].then((data){
    print(data);
    }).timeout(Duration(seconds: 10));

Change this line

httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout());

to

httpRequest.timeout(const Duration (seconds:5),onTimeout : () => _onTimeout());

or just pass a reference to the function (without the ())

httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout);

This way the closure that calls _onTimeout() will be passed to timeout(). In the former code the result of the _onTimeout() call will be passed to timeout()


Using async/await style. You can add .timeout to any Future you are awaiting.

final result = await InternetAddress
   .lookup('example.com')
   .timeout(
      Duration(seconds: 10),
      onTimeout: () => throw TimeoutException('Can\'t connect in 10 seconds.'),
    );

Tags:

Dart

Dart Html