How to pass arguments (besides SendPort) to a spawned isolate in Dart

Issue

In this article, they spawned an isolate like this:

import 'dart:isolate';

void main() async {
  final receivePort = ReceivePort();
  final isolate = await Isolate.spawn(
    downloadAndCompressTheInternet,
    receivePort.sendPort,
  );
  receivePort.listen((message) {
    print(message);
    receivePort.close();
    isolate.kill();
  });
}

void downloadAndCompressTheInternet(SendPort sendPort) {
  sendPort.send(42);
}

But I can only pass in the receive port. How do I pass in other arguments?

I found an answer so I’m posting it below.

Solution

Since you can only pass in a single parameter, you can make the parameter a list or a map. One of the elements is the SendPort, the other items are the arguments you want to give the function:

Future<void> main() async {
  final receivePort = ReceivePort();
  
  final isolate = await Isolate.spawn(
    downloadAndCompressTheInternet,
    [receivePort.sendPort, 3],
  );
  
  receivePort.listen((message) {
    print(message);
    receivePort.close();
    isolate.kill();
  });
  
}

void downloadAndCompressTheInternet(List<Object> arguments) {
  SendPort sendPort = arguments[0];
  int number = arguments[1];
  sendPort.send(42 + number);
}

You’ve lost type safety like this, but you can check the type in the method as needed.

Answered By – Suragch

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *