如何将参数(除了 SendPort)传递给 Dart 中生成的隔离

Sur*_*gch 10 dart dart-isolates

这篇文章中,他们产生了这样的隔离:

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);
}
Run Code Online (Sandbox Code Playgroud)

但我只能传入接收端口。我如何传递其他参数?

我找到了答案,所以我将其发布在下面。

Sur*_*gch 20

由于只能传入单个参数,因此可以将参数设置为列表或映射。其中一个元素是 SendPort,其他项是您想要提供给函数的参数:

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);
}
Run Code Online (Sandbox Code Playgroud)

您已经失去了这样的类型安全性,但您可以根据需要检查方法中的类型。


小智 7

我们可以通过创建带有字段的自定义类来恢复类型安全

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");
}
Run Code Online (Sandbox Code Playgroud)

这样代码会更加干净和安全