How to Write Asynchronous Code Using Future In Dart?

10 minutes read

In Dart, asynchronous code can be written using the Future class, which allows you to represent a potential value or error that may be available at some point in the future. Here is an explanation of how to write asynchronous code using Future in Dart.


To create an asynchronous function that returns a Future, you can prefix the function declaration with the async keyword. Within the function body, you can use the await keyword to pause the execution of the function until a Future completes.


For example, consider the following code snippet:

1
2
3
4
5
6
7
8
9
Future<void> fetchData() async {
  // Simulating an asynchronous task that takes 2 seconds
  await Future.delayed(Duration(seconds: 2));

  // Perform fetching data from a server
  // ...

  print('Data fetched successfully');
}


In the above code, fetchData is an asynchronous function that returns a Future<void>. Inside the function, the await keyword is used to pause the execution for 2 seconds by waiting for the Future.delayed function to complete.


You can also handle errors using try-catch blocks when working with asynchronous code. If the awaited Future throws an exception, it can be caught and handled using regular exception handling techniques.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Future<void> fetchData() async {
  try {
    // Simulating an asynchronous task that takes 2 seconds
    await Future.delayed(Duration(seconds: 2));

    // Perform fetching data from a server
    // ...

    print('Data fetched successfully');
  } catch (e) {
    print('Error: $e');
  }
}


You can also chain multiple asynchronous operations together using .then and .catchError methods of the Future class.

1
2
3
4
5
Future<void> fetchAndProcessData() {
  return fetchSomeData()
      .then((data) => process(data))
      .catchError((error) => handleError(error));
}


In the above code, fetchSomeData returns a Future object, and the .then method is called on it to specify the next operation to be performed when the Future completes successfully. The .catchError method is used to handle any errors that may occur during the asynchronous operations.


Writing asynchronous code using Future in Dart allows you to perform tasks concurrently without blocking the execution of other code. It provides a straightforward and efficient way to handle asynchronous operations in your Dart programs.

Best Dart Books to Read in 2024

1
Flutter and Dart Cookbook: Developing Full-Stack Applications for the Cloud

Rating is 5 out of 5

Flutter and Dart Cookbook: Developing Full-Stack Applications for the Cloud

2
Flutter Cookbook: Over 100 proven techniques and solutions for app development with Flutter 2.2 and Dart

Rating is 4.9 out of 5

Flutter Cookbook: Over 100 proven techniques and solutions for app development with Flutter 2.2 and Dart

3
Quick Start Guide to Dart Programming: Create High-Performance Applications for the Web and Mobile

Rating is 4.8 out of 5

Quick Start Guide to Dart Programming: Create High-Performance Applications for the Web and Mobile

4
Dart: Up and Running: A New, Tool-Friendly Language for Structured Web Apps

Rating is 4.7 out of 5

Dart: Up and Running: A New, Tool-Friendly Language for Structured Web Apps

5
The Dart Programming Language

Rating is 4.6 out of 5

The Dart Programming Language

6
Mastering Dart: A Comprehensive Guide to Learn Dart Programming

Rating is 4.5 out of 5

Mastering Dart: A Comprehensive Guide to Learn Dart Programming

7
Flutter Cookbook: 100+ step-by-step recipes for building cross-platform, professional-grade apps with Flutter 3.10.x and Dart 3.x, 2nd Edition

Rating is 4.4 out of 5

Flutter Cookbook: 100+ step-by-step recipes for building cross-platform, professional-grade apps with Flutter 3.10.x and Dart 3.x, 2nd Edition

8
Flutter for Beginners: An introductory guide to building cross-platform mobile applications with Flutter 2.5 and Dart, 2nd Edition

Rating is 4.3 out of 5

Flutter for Beginners: An introductory guide to building cross-platform mobile applications with Flutter 2.5 and Dart, 2nd Edition


How to handle parallel execution of asynchronous code in Dart?

In Dart, you can handle parallel execution of asynchronous code using various approaches. Here are a few methods you can use:

  1. Future.wait(): Use the Future.wait() method to concurrently wait for multiple asynchronous operations to complete. It takes an iterable of futures and returns a future that completes when all the futures in the iterable complete.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Future<void> main() async {
  List<Future<void>> futures = [
    asyncOperation1(),
    asyncOperation2(),
    asyncOperation3(),
  ];
  
  await Future.wait(futures);
  print('All async operations completed');
}


  1. Future.forEach(): Use Future.forEach() to iterate over a collection and perform an asynchronous operation on each item. It returns a future that completes when all iterations are done.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Future<void> main() async {
  List<String> items = ['item1', 'item2', 'item3'];
  
  await Future.forEach(items, (item) async {
    await asyncOperation(item);
    print('Async operation on $item completed');
  });
  
  print('All async operations completed');
}


  1. Completer: Use a Completer to create a custom logic for parallel execution. You can create multiple Completer objects, execute async operations, and manually complete the Completer when the operation completes.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
Future<void> main() async {
  Completer<void> completer1 = Completer<void>();
  Completer<void> completer2 = Completer<void>();

  asyncOperation1().then((_) {
    completer1.complete();
    print('Async operation 1 completed');
  });

  asyncOperation2().then((_) {
    completer2.complete();
    print('Async operation 2 completed');
  });

  await Future.wait([completer1.future, completer2.future]);
  print('All async operations completed');
}


These methods allow you to execute multiple asynchronous operations concurrently and wait for all of them to complete before continuing further in the code. Choose the method that best fits your use case.


How to create a Future object in Dart?

To create a Future object in Dart, you can use the Future constructor or the Future.value constructor.

  1. Using the Future constructor: Future getData() { return Future(() { // Perform async task here return 'Data fetched successfully'; }); } In this example, the getData() function returns a Future, which is created using the Future constructor. Inside the constructor, you can perform any asynchronous task, such as making an HTTP request or reading a file, and return the result using the return statement.
  2. Using the Future.value constructor: Future getData() { return Future.value('Data fetched successfully'); } Alternatively, you can create a Future object using the Future.value constructor, which directly returns a completed Future with a specified value. In this example, the getData() function returns a completed Future with the value 'Data fetched successfully'.


Both methods allow you to create Future objects in Dart, allowing you to handle asynchronous operations and await their completion.


How to write asynchronous code using Future in Dart?

To write asynchronous code using Future in Dart, you can follow these steps:

  1. Create a function that returns a Future object. This function will perform asynchronous tasks and return the result when it is ready.
1
2
3
Future<int> getData() {
  return Future.delayed(Duration(seconds: 2), () => 42);
}


  1. Use the then() method on the Future object or the await keyword to handle the result once it is ready. The then() method allows you to chain multiple asynchronous operations.
1
2
3
getData().then((result) {
  print(result); // 42
});


or

1
2
3
4
void main() async {
  int result = await getData();
  print(result); // 42
}


  1. To handle errors, use the catchError() method on the Future object or use a try-catch block with the await keyword.
1
2
3
getData().catchError((error) {
  print('Error: $error');
});


or

1
2
3
4
5
6
7
8
void main() async {
  try {
    int result = await getData();
    print(result); // 42
  } catch (error) {
    print('Error: $error');
  }
}


By using the Future class and its methods, you can write and handle asynchronous code in Dart efficiently.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

To invoke Dart code from Kotlin code, you can use the platform channel provided by Flutter. This allows communication between the Dart and Kotlin code in your app.First, define a method in your Dart code that you want to invoke from Kotlin. Then, create a Meth...
Dart DevTools is a powerful tool for debugging Dart applications. It provides a comprehensive set of features to help you understand and analyze the behavior of your code during runtime. Here&#39;s an overview of how to use Dart DevTools for debugging:Installa...
To send emails via Gmail from Dart, you can use the mailer package. Here are the steps to achieve this:Set up your Dart project by creating a new Dart file and importing the necessary packages. import &#39;package:mailer/mailer.dart&#39;; import &#39;package:m...