Conversation


Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0


advertisement

Asynchronous Programming with Future Keyword

dart keyword


The future keyword is used for getting a value sometime in the future. The asynchronous function returns Future, which contains the result. Future objects are a mechanism to represent values returned by an expression whose execution will be completed at a particular point in time.

The future function has three states:

  • Uncompleted: In this state, the output is closed.
  • Completed with value: In this state, the output is open and the data is ready.
  • Completed with an error: In this state, the output is open and something went wrong.


a. Future Value:

Future value creates a future with value. If the value is a future, the created future waits for the value to execute and then it is executed with the same result.

import 'dart:async';

void main(){
var myfutureval = Future.value(10);
print(myfutureval);
}


b. Future error:

Future error creates a future, which completes with an error.

import 'dart:async';

void main(){
Future<int> getFuture(){
  return Future.error("This is an error");
  }
 getFuture();
}


c. Future delayed:

Future delay creates a future, which runs its computation after a delay. Future delay always works with a certain amount for the duration. Computation will be executed after a given duration has passed.

import 'dart:async';

void main(){
Future.delayed(Duration(milliseconds: 10000),(){
print("This is a delayed future");
});
}



Asynchronous programming with the Async keyword

The async keyword is used when declaring a function as asynchronous. The async keyword is added after the function name. When an async function is called, the Future is returned and the function is executed.

Function_name() async{
}



Asynchronous programming with the Await keyword

The await keyword is used only in an asynchronous function. The await keyword holds the currently running function until the result is ready. If the result is ready, then it continues execution on the next line of code. 

import 'dart:async';

void main() async{
demo() async{
 print("Good Morning");
 }
 await demo();
 print("Have a great day!");
}

Dart Future keyword Await keyword Async keyword asynchronous programming

advertisement