setController method Null safety

void setController(
  1. StreamController<T>? controller
)

Changes the stream controller for this event channel.

Setting the controller to null disconnects from the channel (setting the message handler on the binaryMessenger to null).

Implementation

void setController(StreamController<T>? controller) {
  final BinaryMessenger messenger = binaryMessenger ?? pluginBinaryMessenger;
  if (controller == null) {
    messenger.setMessageHandler(name, null);
  } else {
    // The handler object is kept alive via its handle() method
    // keeping a reference to itself. Ideally we would keep a
    // reference to it so that there was a clear ownership model,
    // but that would require making this class non-const. Having
    // this class be const is convenient since it allows references
    // to be obtained by using the constructor rather than having
    // to literally pass references around.
    final _EventChannelHandler<T> handler = _EventChannelHandler<T>(
      name,
      codec,
      controller,
      messenger,
    );
    messenger.setMessageHandler(name, handler.handle);
  }
}