Skip to content

Platform message handler callback crashes when background task queue is used and dynamic actor isolation is on. #184737

Description

@LongCatIsLooong

Dynamic actor isolation (implemented in Swift 6) inserts runtime assertions into Swift callbacks if the callback is supposed to be @MainActor-isolated. The Flutter message channels API (and the FlutterBinaryMessenger class) typically takes a taskQueue parameter which if not nil, the FlutterEngine is going to invoke the callback on the thread represented by the taskQueue (and that thread usually isn't the main thread).

So when the user does this in their Swift app:

func didInitializeImplicitFlutterEngine(_ engineBridge: any FlutterImplicitEngineBridge) {
  GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
  let channel = FlutterMethodChannel(
    name: "channel",
    binaryMessenger: engineBridge.applicationRegistrar.messenger(),
    codec: FlutterJSONMethodCodec.sharedInstance(),
    taskQueue: engineBridge.applicationRegistrar.messenger().makeBackgroundTaskQueue?(),
  )
  
  channel.setMethodCallHandler { (call: FlutterMethodCall, result: FlutterResult) -> Void in
    result(nil)
  }
}

and send a message to this channel in the dart program:

  const MethodChannel('channel', JSONMethodCodec()).invokeMethod('message');

The program crashes (even in production) with this stacktrace, when "dynamic actor isolation" is on:
Image

Impact

I couldn't find any related github issues.

List of code on Github that uses the makeBackgroundTaskQueue API.

"Dynamic actor isolation" is on by default if you set the Swift language version to 6:

Image

Workaround

Tell the compiler the closure is @Sendable

  channel.setMethodCallHandler { @Sendable (call: FlutterMethodCall, result: FlutterResult) -> Void in
    result(nil)
  }

Turn off dynamic actor isolation in release mode.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work listplatform-iosiOS applications specificallyteam-iosOwned by iOS platform teamtriaged-iosTriaged by iOS platform team

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions