Is DartDocs about the entry of `Isolate.spawn` wrong or something?

Viewed 33

I'm using Dart 2.18.0 now. Here's what the docs say about the entry of Isolate.spawn.

The function must be a top-level function or a static method that can be called with a single argument, that is, a compile-time constant function value which accepts at least one positional parameter and has at most one required positional parameter. The function may accept any number of optional parameters, as long as it can be called with just a single argument. The function must not be the value of a function expression or an instance method tear-off.

Here's the code I write,

import 'dart:io';
import 'dart:isolate';

void main(List<String> args) {
  Isolate.spawn((message) {
    print("$message ${Isolate.current.debugName}");
  }, "Hello world!", debugName: "block");
  final p = Person();
  Isolate.spawn(p.saySomething, "Nice to meet you!",
      debugName: "Object method");
  Isolate.spawn(
      p.saySomething2(), "A function from the value of a function expression!",
      debugName: "Function Expression");
  sleep(Duration(seconds: 1));
}

class Person {
  void saySomething(String something) {
    print("$something ${Isolate.current.debugName}");
  }

  void Function(String message) saySomething2() {
    return saySomething;
  }
}

See, I pass a block and a method of a instance to each Isolate.spawn. The code runs well and it prints the following logs.

Hello world! block
Nice to meet you! Object method
A function from the value of a function expression! Function Expression

But how? Block is neither a top level function nor a static function. The function from a value of a function expression and the method of an instance can also be passed as Isolate entry.

Do I get it wrong? Or these features has been supported, the doc has not updated yet?

1 Answers

I think the problem here is that you're passing a function as a parameter, when

Isolate.spawn

expects a function expression. The docs say:

The function must be a top-level function or a static method that can be called with a single argument, that is, a compile-time constant function value which accepts at least one positional parameter and has at most one required positional parameter. The function may accept any number of optional parameters, as long as it can be called with just a single argument. The function must not be the value of a function expression or an instance method tear-off.

You can see an example of a function expression in the docs here:

int foo(int a, int b) => a + b;

Your

saySomething2

Function returns a function expression, so you can use that directly:

Isolate.spawn(p.saySomething2(), "A function from the value of a function expression!", debugName: "Function Expression");

Related