How can I "sleep" a Dart program

Vinnie picture Vinnie · Aug 26, 2013 · Viewed 72k times · Source

I like to simulate an asynchronous web service call in my Dart application for testing. To simulate the randomness of these mock calls responding (possibly out of order) I'd like to program my mocks to wait (sleep) for a certain period of time before returning the 'Future'.

How can I do this?

Answer

Shailen Tuli picture Shailen Tuli · Aug 26, 2013

You can also use the Future.delayed factory to complete a future after a delay. Here is an example of two functions that return a string asynchronously after a delay:

import 'dart:async';

Future sleep1() {
  return new Future.delayed(const Duration(seconds: 1), () => "1");
}

Future sleep2() {
  return new Future.delayed(const Duration(seconds: 2), () => "2");
}