Skip to main content

Multithreading in flutter!

Now, some of you might be wondering—Wait, what? Multithreading in Flutter? Yes, that’s correct! Flutter is fully capable of handling multithreading. While Flutter primarily relies on the main thread for rendering and performing other tasks, modern mobile processors come equipped with multiple threads, so why not take advantage of them?

Some of you may be asking, why do we even need additional threads when the main thread can handle most tasks just fine? And I agree, the main thread can indeed manage a lot of work. However, when it comes to performance-heavy operations like complex computations or intensive data processing, you might notice that your app's UI starts to freeze, or you experience frame drops. This is where multithreading becomes the ideal solution, helping to offload these tasks and keep your UI responsive.

Isolates

Before diving into multithreading in Flutter, it's essential to first understand Isolates. Unlike traditional multithreading, where threads share memory and can lead to issues like race conditions and deadlocks, Flutter takes a different approach to concurrency using Isolates.

Isolates are independent execution units that run code in parallel to the main application. Each isolate operates in its own memory space, with its own event loop, completely isolated from other isolates and the main thread. This design ensures that there is no shared memory between isolates, which effectively eliminates many common concurrency problems that are prevalent in traditional multithreading, such as race conditions, deadlocks, and resource contention.

The key to communication between isolates is message passing. Since isolates don't share memory, they rely on sending and receiving messages through ports (SendPort and ReceivePort) to coordinate tasks. This message-passing architecture ensures that isolates can perform concurrent tasks without affecting each other's state, making it easier to write error-free concurrent code.

import 'dart:isolate';

void backgroundTask(SendPort sendPort) {
int result = 0;
for (int i = 0; i < 1000000000; i++) {
result += i;
}
sendPort.send(result);
}

void main() async {
  ReceivePort receivePort = ReceivePort();

await Isolate.spawn(backgroundTask, receivePort.sendPort);

receivePort.listen((result) {
print(
result);
},
 );
}

Compute Function

The Compute function, provided by the flutter/foundation.dart package, is a utility that allows you to offload long-running, computationally intensive tasks to a background Isolate. Rather than executing these tasks on the main UI thread, Compute spawns a new Isolate, ensuring that the UI remains smooth and responsive during the process. Once the background task is completed, the result is passed back to the main thread.

For resource-heavy operations such as data processing, JSON parsing, or file I/O, you can use the Compute function to handle these tasks in the background. It creates an Isolate specifically for the task, preventing the main thread from being blocked. The background isolate performs the computation independently, and once it finishes, the result is communicated back to the main isolate through message passing.

In essence, the Compute function leverages Isolates to efficiently manage heavy workloads, maintaining the performance and responsiveness of your app.

import 'package:flutter/foundation.dart'; 

int backgroundTask(int value) {
int result = 0;
for (int i = 0; i < value; i++) {
result += i;
}
return result;
}

void main() async {
int result = await compute(backgroundTask, 1000000000);

print(result);
}

Flutter's compute function and isolates provide a powerful and efficient way to handle heavy computational tasks without compromising the performance of your app's user interface. By offloading resource-intensive operations, you can keep the main thread unblocked and ensure a smooth, responsive user experience. 

In my next blog post, I will try to demonstrate a practical example of implementing multithreading in Flutter, showcasing how to efficiently manage both UI updates and background tasks simultaneously.

Comments

Popular posts from this blog

Understanding BuildContext in Flutter!

As a Flutter developer, you might have encountered the term BuildContext early in your journey. Despite its importance, many developers struggle to grasp its full significance. Today, we’re going to dive into what BuildContext is, what it does, and why it’s crucial for running your Flutter app. What is BuildContext In both stateless and stateful widgets, when you override the build method, it takes BuildContext context as a parameter. This context is provided by the Flutter framework. Here’s a simple example to illustrate: Widget build(BuildContext context) { return OutlinedButton( onPressed: () async { await Future< void >.delayed( const Duration(seconds: 1 )); if (context.mounted) { Navigator.of(context).pop(); } }, child: const Text( 'Delayed pop' ), ); } BuildContext do a simple task, track all of your widget location. In flutter, it all about widgets. Everything is build on a collection of widgets. Some widgets are parent w

Impeller: Elevating Flutter Performance with Predictable Rendering

In the world of Flutter, Impeller is a buzzword that has caught the attention of developers and enthusiasts alike. But what exactly is Impeller, and why is it crucial for Flutter apps? Let’s dive into the details. What is Impeller? Impeller is a new rendering engine for flutter. Now, many of you can think. What is a rendering engine. Rendering engine is nothing but a piece of software responsible for converting input instructions or data into visual or audible output. Basically , it helps us to draw UI of an app according to the instruction you give it. Flutter engine is written is C/C++language. Which is the part of dart UI. Rendering engine in Flutter orchestrates the transformation from widget tree to pixels on the screen. Before Impeller flutter used skia as a default graphics engine. But, there was some issues on it. Challenges with Skia: Skia has been the graphic engine for Flutter since its inception. Skia is also a powerful render engine, which powers various platforms, inc