Skip to main content

Exploring Parallelism on Flutter: Main Thread, Isolate and Compute

SR
Sabin Ranabhat
Published February 4, 2024•3 min read
Exploring Parallelism on Flutter: Main Thread, Isolate and Compute

Exploring Parallelism on Flutter

Main Thread: We all know Dart (Flutter) code runs in a single thread, which is a main thread aka main isolate. This thread is responsible for painting UI, handling user interaction and responding to the user interactions. Below you can see an example where I am fetching data on the main thread, that might overload the main thread and lead to sluggish performance and unresponsive UI, causing a jarring experience for users.

// Fetching data using main thread
Future<void> fetchData() async {
  // Simulating a heavy task on the main thread
  var result = await heavyComputation();
  print(result);
}

Future<String> heavyComputation() async {
  // This blocks the main thread!
  var total = 0;
  for (var i = 0; i < 1000000000; i++) {
    total += i;
  }
  return "Done: $total";
}

Isolate: Dart introduces Isolate to achieve true parallelism. Isolate has its own memory space that allow to perform computation without blocking the main thread. Communication between isolates is done using ports: ‘SendPort’ and ‘ReceivePort’. Below is an example of isolate where I am fetching data using isolate without hampering the main thread.

// Fetching data using isolate thread
import 'dart:isolate';

Future<void> fetchDataInIsolate() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(heavyComputationIsolate, receivePort.sendPort);

  receivePort.listen((message) {
    print(message);
    receivePort.close();
  });
}

void heavyComputationIsolate(SendPort sendPort) {
  var total = 0;
  for (var i = 0; i < 1000000000; i++) {
    total += i;
  }
  sendPort.send("Done: $total");
}

Compute: Just above we read about isolates. Now, what is ‘compute’? Isolate provides parallelism, but, manually handling them could be a tedious task, so Dart has provided us a compute method which provides parallelism without having to create ports like in the isolates. Below is an example of a compute method from which I am fetching data.

// Fetching data using compute method
import 'package:flutter/foundation.dart';

Future<void> fetchDataWithCompute() async {
  var result = await compute(heavyComputation, 1000000000);
  print(result);
}

String heavyComputation(int iterations) {
  var total = 0;
  for (var i = 0; i < iterations; i++) {
    total += i;
  }
  return "Done: $total";
}

Performance

I tested all three ways to fetch the data and here’s the result. Isolate is faster than others.

(Note: Performance metrics would typically be displayed here, showing Isolate/Compute outperforming the Main Thread for heavy tasks)

Choosing the Right Tool for the Job

  • Main thread: Stick to UI updates, animations, and user interactions.
  • Isolates: Use for computationally intensive tasks, network requests, and background processing.
  • Compute: Ideal for short-lived, simple calculations. And when you don't want to configure Isolates 🤣

Things to remember

  • Communication: Isolates require message passing for communication, while compute doesn't.
  • Complexity: Isolates offer more control but require more setup, while compute is simpler but less flexible.
  • Memory: Isolates have separate memory spaces, while compute shares the main thread's memory.

Conclusion

Understanding the nuances of main thread, isolates, and compute empowers you to make informed decisions about concurrency in your Flutter projects. By leveraging these tools strategically, you can ensure a smooth, responsive, and performant user experience, taking your Flutter apps to the next level!

Bonus Tip: Experiment with different approaches and measure performance to find the optimal solution for your specific use case.

I hope this article provides a clear and concise explanation of these concurrency concepts in Flutter. Feel free to ask if you have any further questions or need more specific examples!. Please do share your feedback and comments below! Your insights contribute to a vibrant community of Flutter developers.

For More

Share this article:
Sabin Ranabhat

Written by Sabin Ranabhat

I'm a Senior Software Engineer specializing in full-stack development with TypeScript, React, Next.js and Node.js, with deep Flutter, iOS, and Android experience. I'm currently open to new remote roles and challenges. If you need a specialist to lead your full-stack development, let's talk.

Related Posts