Examples Of Async

  • Example 1:

  • The Future.value creates a future completed with value.


    void main() async {

      var f1 = Future.value(50);

      print(f1);

     

      var f2 = await Future.value(50);

      print(f2);

    }



    Instance of 'Future'
    50

    In this example, the main function contains two futures so we mark it with the async keyword.

    f1 is a future with value but not a completed instance of the future because we didn't use the await.

    f2 is the same as f1 but we add the await keyword and now it's completed.


  • Example 2:

  • The Future.delayed creates a future that runs its computation after a delay.


    void main() async {

      Future.delayed(Duration(seconds: 3), () => 404).then((value) => print(value));

     

      final res = await Future.delayed(Duration(seconds: 5), () => 666);

      print(res);

    }



    404     //after 3 sec
    666     //after 5 sec

    In this example, we create two delayed futures the first is executed after 3s and the second after 5s.

    The first use .then() as a callback to print the value when the future is completed without storing the result.

    The second use the await keyword and store the result in res.


  • Example 3:

  • The Future.wait waits for multiple futures to complete and collects their results. It returns a future which completes once all the given futures have completed.

    import 'dart:async';

    import 'dart:math';

     

    Future<intgetRandomNumber(int x) async {

      await Future.delayed(Duration(seconds: 1));

      return Random().nextInt(x);

    }

     

    double findAverage(List<int> list) {

      int sum = 0;

      list.forEach((e) => sum += e);

      return sum / list.length;

    }

     

    void main() async {

      final average = await Future.wait([

        getRandomNumber(250),

        getRandomNumber(250),

        getRandomNumber(250),

        getRandomNumber(250),

        getRandomNumber(250),

        getRandomNumber(250)

      ]).then((List<int> res) {

        print(res);

        return findAverage(res);

      });

      print('The average : $average');

    }



    [103, 189, 154, 222, 136, 69]
    The average : 145.5

    In this example, we use an asynchronous function multiple time to generate a random number each 1 second.

    We place all the futures inside a Future.wait then we pass the result to findAverage method when all the futures are completed.