Sobes.tech
Middle

What is an Isolate in Flutter?

sobes.tech AI

Answer from AI

Isolate is an independent working unit in Flutter, similar to a thread but with an important difference: each Isolate has its own memory space, which prevents data race issues.

Key points:

  • They run in parallel.
  • They do not share memory directly.
  • They communicate through ports (SendPort and ReceivePort), sending and receiving messages.
  • The main Isolate (UI Isolate) is responsible for rendering the UI and handling events.
  • New Isolates are created to perform resource-intensive tasks without blocking the UI.

Example usage:

import 'dart:isolate';

void heavyTask(SendPort sendPort) {
  var result = 1;
  for (var i = 1; i <= 1000000; i++) {
    result *= i; // Performing a heavy operation
  }
  sendPort.send(result); // Sending the result back
}

void main() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(heavyTask, receivePort.sendPort);

  receivePort.listen((message) {
    print('Result of heavy task: $message');
  });
}
What is an Isolate in Flutter? — Flutter - sobes.tech