Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
dart
futures

Having fun with futures in Dart

Kuti Gbolahan

By now, you probably realize that in order to do async programming in Dart, you must work with futures. So, it would be good to know your way around that class. Let’s take some scenarios and show how the Future class in Dart handles them:

  • Iterating a list of async calls in order.
  • Waiting for all async calls to complete
  • Error Handling

Iterating

To iterate a set of async calls, use Future.forEach. In the example below, we create a method to check if a number is prime or not. Since we wrap our result coming from isPrimeNumber in a Future, we are able to await the results and invoke them so that we can perform an operation of our choosing against that result (in our case, we just print out for the result).

import 'dart:async';
import 'dart:math';

Future<bool> isPrimeNumber(int number) async {  
  if (number == 1) return false;
  if (number == 2) return true;

  double mysqrt = sqrt(number);
  int limit = mysqrt.ceil();

  for (int i = 2; i <= limit; ++i)  {
    if (number % i == 0)  return false;
  }

  return true;
}

void main() async {
  await Future.forEach([1,2,3,4,5,6,7,8,9,10], (int n) => 
    isPrimeNumber(n)
    .then((x) => print("${n}${x ? " is" : " is not"} a prime number")));
  
  print('done!');
}

Error handling

Dart makes handling errors within asynchronous code easy because it utilizes something you are most likely already very familiar with, try-catch blocks. If the code within a try block throws an exception, you are going to be able to handle it in the catch block.

In the example below, we intentionally throw an exception in the openFile function, just to see how it works. If you run this, you would see that the “success!” message is never printed and that, instead, we see a message concerning the exception that was thrown.

import 'dart:async';
Future<void> openFile(String fileName) async {
  throw new Exception("boom!");
}
void main() async {
  try
  {
    var result = await openFile("theFile");
    print("success!");
  }
  catch(e) {
    print("Looks like we caught an error: ${e.toString()}");
  }
}

Combined with the Future class, the async/await pattern in Dart is a powerful and expressive way of doing asynchronous programming. This is good news because, as you get into building web applications or Flutter, you are going to really need to grasp the fundamentals of asynchronous coding.

RELATED TAGS

communitycreator
dart
futures
RELATED COURSES

View all Courses

Keep Exploring