Future in Dart

What is Future object?

Future object is to represent a delayed computation, i.e a potential value, or error, that will be available at some time in the future.

For example, this code delayed for 2 seconds to return the list of strings.

Future products() {
  // return (future of) list delayed for 1 second
  return Future.delayed(
    Duration(seconds: 1),
    () => ['product 1', 'product 2', 'product 3', 'product 4'],
  );
}

Receivers of a Future can register callbacks that handle the value or error once it is available.

For example: register then callback to handle the value, and catchError callback to handle error.

// Register callback, to be called when this future completes.
  products().then((value) {
    print(value);
  }).catchError(
    // Handles errors emitted by this Future
    (error) {
      print('catching $error');
    },
  );

Future example code

import 'dart:async';

Future products() {
  // return (future of) list delayed for 1 second
  return Future.delayed(
    Duration(seconds: 1),
    () => ['product 1', 'product 2', 'product 3', 'product 4'],
  );
}

main() {
  // Register callback, to be called when this future completes.
  products().then((value) {
    print(value);
  }).catchError(
    // Handles errors emitted by this Future
    (error) {
      print('catching $error');
    },
  );
}