In Dart, we can execute asynchronous code by using a variety of classes and keywords such as Future
.
A Future
allows us to execute asynchronous programs.
Note: A program code can accomplish tasks while awaiting the completion of another action thanks to asynchronous operations.
A Future
primarily represents the outcome of an asynchronous operation.
An asynchronous operation includes the following:
In Dart, a Future
has two states:
Completed: When an asynchronous operation on a Future
is finished, the Future
successfully completes with a value. Otherwise, it completes unsuccessfully with an error.
Uncompleted: When an asynchronous operation is called, it queues up and returns an unfinished Future
.
Note: In Dart, the state of a
Future
before it has generated a value is referred to as being uncompleted.
Future<T>
The return type is void if the Future
does not yield any value.
The following code shows how to use Future
in Dart.
// getWriterName function of type `Future` which computes a future// the return type is StringFuture<String> getWriterName() {// 3 seconds delay to simulate a call to cloud storage or dbreturn Future.delayed(Duration(seconds: 3), () => "Maria Elijah");}void main() {print('Welcome to Educative!');var writerName = getWriterName();// create a callbackwriterName.then((name) => print("The writer's name is $name"));print('Keep Learning!');}
Line 3-6: We create a function called getWriterName()
of the Future
type. This function computes a Future
and returns a String
.
Line 9: We define the main()
function.
Line 10: We use print()
to display a statement.
Line 11: We assign the getWriterName()
function to a new variable called writername
.
Line 13: We create a callback
to display the Future
value (in our case, the value is the writer’s name).
Line 14: We use print()
to display a statement.
Note: The
print()
function on line 14 was executed before thecallback
because thegetWriterName()
function is an asynchronous operation.
// displayGreetings function of type `Future` which computes a future// the return type is voidFuture<void> displayGreetings() {// 3 seconds delay to simulate a call to cloud storage or dbreturn Future.delayed(Duration(seconds: 3), () => print('Welcome to Educative!'));}void main() {// call the futuredisplayGreetings();print('Keep Learning!');}
Line 4-7: We create a function called displayGreetings()
of the Future
type. This function computes a Future
and returns void
.
Line 10: We define the main()
function.
Line 11: We call the displayGreetings()
function.
Line 13: We use print()
to display a statement.
Free Resources