
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Future Class in Dart Programming
There are different classes and keywords in Dart which we can use when we want to run Asynchronous code. The future class allows us to run asynchronous code and we can also avoid the callback hell with the help of it. A future mainly represents the result of an asynchronous operation.
In Dart, there are many standards library calls that return a future, some of them are −
http.get
SharedPreference.getInstance()
A future in Dart can have two states, these are −
Completed - When the operation of the future finishes and the future complete with a value or with an error.
Uncompleted - When a function is called, and it returned a future, the function queues up and returns an uncompleted future.
Syntax
Future<T>
In Dart, if a future doesn't produce any usable value then the future's type is Future<void>. Also, if the function doesn't explicitly return any value, then the return type is also Future<void>.
Example
Let's consider a small example where we are declaring a future that will display a message in a delayed fashion.
Consider the example shown below: Future<void> printDelayedMessage() { return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.')); } void main() { printDelayedMessage(); print('First output ...'); }
In the above example, we have a function named printDelayedMessage() that returns a future of type void, and we have a future that is using a method named delayed through which we are able to print the delayed output to the terminal.
Output
First output ... Delayed Output.
It should be noted the second line of the output will be printed after 4 seconds.
Futures in Dart also allows us to register callbacks with the help of the then methods.
Example
Consider an example shown below −
void main() { var userEmailFuture = getUserEmail(); // register callback userEmailFuture.then((userId) => print(userId)); print('Hello'); } // method which computes a future Future<String> getUserEmail() { // simulate a long network call return Future.delayed(Duration(seconds: 4), () => "[email protected]"); }
Output
Hello [email protected]