Concurrent programming using isolates for parallel execution
The dart:isolate library enables concurrent programming using isolates: independent workers that are similar to threads but don’t share memory, communicating only via messages.
Platform Availability: dart:isolate is currently only supported by the Dart Native platform (VM, AOT, and Flutter). It is not available on the web.
Spawns a new isolate that runs a specified function.
import 'dart:isolate';// Entry point function for the isolatevoid isolateFunction(SendPort sendPort) { // Do some work var result = expensiveComputation(); // Send result back to main isolate sendPort.send(result);}Future<void> main() async { // Create a receive port for getting messages var receivePort = ReceivePort(); // Spawn the isolate await Isolate.spawn(isolateFunction, receivePort.sendPort); // Wait for the result var result = await receivePort.first; print('Result: $result');}int expensiveComputation() { // Simulate heavy computation var sum = 0; for (var i = 0; i < 1000000000; i++) { sum += i; } return sum;}
import 'dart:isolate';// Worker isolate that processes messagesvoid workerIsolate(SendPort mainSendPort) { // Create receive port for this isolate var workerReceivePort = ReceivePort(); // Send our send port to main isolate mainSendPort.send(workerReceivePort.sendPort); // Listen for messages from main workerReceivePort.listen((message) { if (message is Map) { var command = message['command']; var data = message['data']; var replyPort = message['replyPort'] as SendPort; // Process the command var result = processCommand(command, data); // Send result back replyPort.send(result); } });}Future<dynamic> sendToWorker( SendPort workerSendPort, String command, dynamic data,) async { var responsePort = ReceivePort(); // Send message with reply port workerSendPort.send({ 'command': command, 'data': data, 'replyPort': responsePort.sendPort, }); // Wait for response return await responsePort.first;}Future<void> main() async { var mainReceivePort = ReceivePort(); // Spawn worker await Isolate.spawn(workerIsolate, mainReceivePort.sendPort); // Get worker's send port var workerSendPort = await mainReceivePort.first as SendPort; // Send commands to worker var result1 = await sendToWorker(workerSendPort, 'process', [1, 2, 3]); print('Result 1: $result1'); var result2 = await sendToWorker(workerSendPort, 'compute', {'x': 10, 'y': 20}); print('Result 2: $result2');}dynamic processCommand(String command, dynamic data) { switch (command) { case 'process': return (data as List).fold(0, (a, b) => a + b); case 'compute': var map = data as Map; return map['x'] + map['y']; default: return 'Unknown command'; }}
Sends messages to a ReceivePort. Can be sent between isolates.
// Create receive portvar receivePort = ReceivePort();// Get the send portvar sendPort = receivePort.sendPort;// Listen for messagesreceivePort.listen((message) { print('Received: $message');});// Send a message (from another isolate)sendPort.send('Hello');sendPort.send(123);sendPort.send({'key': 'value'});sendPort.send([1, 2, 3]);// Close port when donereceivePort.close();
Flutter helper function that spawns an isolate, runs a computation, and returns the result.
import 'package:flutter/foundation.dart';// Top-level or static functionint fibonacci(int n) { if (n < 2) return n; return fibonacci(n - 1) + fibonacci(n - 2);}Future<void> main() async { // Run computation in separate isolate var result = await compute(fibonacci, 40); print('Fibonacci(40) = $result');}// With custom dataclass ComputeData { final int start; final int end; ComputeData(this.start, this.end);}int sumRange(ComputeData data) { var sum = 0; for (var i = data.start; i <= data.end; i++) { sum += i; } return sum;}Future<void> example() async { var result = await compute(sumRange, ComputeData(1, 1000000)); print('Sum: $result');}