Sobes.tech
Middle

What are Future constructors in Flutter and how to use them?

sobes.tech AI

Answer from AI

The Future constructors in Flutter are used to create Future objects that represent the result of an asynchronous operation that may be completed in the future. They help manage the flow of asynchronous code.

Main constructors:

  • Future(): Creates a Future that will be executed after the current microtask completes. Useful for scheduling tasks after the current event loop.

    Future(() {
      // Asynchronous operation
      print('This runs after the current microtask.');
    });
    
  • Future.delayed(Duration duration, [FutureOr<T> computation()]): Creates a Future that will be executed after the specified delay. computation is an optional function that executes after the delay and returns a Future value.

    Future.delayed(Duration(seconds: 2), () {
      print('This runs after 2 seconds.');
    });
    
  • Future.value([FutureOr<T>? value]): Creates a Future that is already completed with the specified value. If the value is another Future, this constructor will wait for its completion.

    Future<int>.value(123).then((value) => print('Value is: $value'));
    
  • Future.error(Object error, [StackTrace? stackTrace]): Creates a Future that is already completed with the specified error.

    Future.error('Something went wrong').catchError((error) => print('Error: $error'));
    
  • Future.sync(FutureOr<T> computation()): Creates a Future that executes the computation synchronously immediately. If the computation returns a Future, this constructor will wait for its completion.

    Future.sync(() {
      print('This runs synchronously.');
      return 456;
    }).then((value) => print('Sync value: $value'));
    

Using then, catchError, and whenComplete to handle the result:

Future.delayed(Duration(seconds: 1), () => 'Hello, World!')
    .then((result) {
      // Executes on success
      print(result);
    })
    .catchError((error) {
      // Executes on error
      print('An error occurred: $error');
    })
    .whenComplete(() {
      // Executes regardless of success or error
      print('Future completed.');
    });
What are Future constructors in Flutter and how to… - sobes.tech