Skip to main content
almarefa.net

Back to all posts

How to Write Asynchronous Code Using Future In Dart?

Published on
5 min read

Table of Contents

Show more
How to Write Asynchronous Code Using Future In Dart? image

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:

Future 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.

Future 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.

Future 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.

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.

Future main() async { List<Future> 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.

Future main() async { List 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.

Future main() async { Completer completer1 = Completer(); Completer completer2 = Completer();

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.

Future 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.

getData().then((result) { print(result); // 42 });

or

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.

getData().catchError((error) { print('Error: $error'); });

or

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.