Dart/Flutter: How to use a Future with a Duration delay

As a quick note, here are two examples of how to use a Future with a Duration delay in Dart (and Flutter):

// example 1
Future<bool> _getFutureBool() {
    return Future.delayed(Duration(milliseconds: 500))
        .then((onValue) => true);
}

// example 2
print('1');
Future.delayed(const Duration(milliseconds: 500), () {
    print('Hello, world');
});
print('2');

If you’re comfortable with Dart futures, you know that the second example will (eventually) print this output:

1
2
Hello, world

A complete example

While I’m in the neighborhood, here’s a complete example using Dart 2.15.1 in January, 2022:

import 'dart:async';

Future<int> async1() {
    return Future.delayed(Duration(milliseconds: 1000))
        .then((onValue) => 1);
}

Future<int> async2() {
    return Future.delayed(Duration(milliseconds: 2000))
        .then((onValue) => 2);
}

Future<int> async3() {
    return Future.delayed(Duration(milliseconds: 3000))
        .then((onValue) => 3);
}

void main() {
    var t1 = DateTime.now();
    Future.wait([async1(), async2(), async3()])
        .then((List<int> nums) {
            var t2 = DateTime.now();
            var sum = nums.reduce((curr, next) => curr + next);
            print('sum = $sum');
            print('delta = ${t2.difference(t1)}');  // should be 3, not 6
        });  
}

When you run this Dart app with the Unix time command, you should see that the sum is 6, and it’s returned in about three seconds:

> time dart Futures.dart
sum = 6
delta = 0:00:03.022795

real    0m3.491s
user    0m0.574s
sys    0m0.134s

It’s returned in about three seconds because that’s the longest wait time I specify. This confirms that the futures run in parallel. Had they run in sequence, one after the other, the total time would be about six seconds (the sum of the three wait times).

If you needed a Dart future/parallel example, I hope this helps.