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

2

10

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.

Item answered 2/9, 2020 at 14:1 Comment(0)
I
22

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.

Item answered 2/9, 2020 at 14:1 Comment(1)
You should make the List of type dynamic not Object.Gera
C
7

We can get back the type safety by creating a custom class with fields

class RequiredArgs {
   final SendPort sendPort;
   final int id;
   final String name;

   RequiredArgs(this.sendPort, this.id, this.name);
 }

void downloadAndCompressTheInternet(RequiredArgs args) {
  final sendPort = args.sendPort;
  final id = args.id;
  final name = args.name;

  sendPort.send("Hello $id:$name");
}

Code will be much cleaner and safer in this way 🥸

Cymogene answered 13/5, 2022 at 7:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.