setMockStreamHandler method

void setMockStreamHandler(
  1. EventChannel channel,
  2. MockStreamHandler? handler

Set a handler for intercepting stream events sent to the platform on the given channel.

Intercepted method calls are not forwarded to the platform.

The given handler will replace the currently registered handler for that channel, if any. To stop intercepting messages at all, pass null as the handler.

Events are decoded using the codec of the channel.

The handler's stream messages are used as a response, after encoding them using the channel's codec.

To send an error, pass the error information to the handler's event sink.

It is strongly recommended that all handlers used with this API be synchronous (not requiring any microtasks to complete), because testWidgets tests run in a FakeAsync zone in which microtasks do not progress except when time is explicitly advanced (e.g. with WidgetTester.pump), which means that awaiting a Future will result in the test hanging.

Registered handlers are cleared after each test.

See also:


void setMockStreamHandler(EventChannel channel, MockStreamHandler? handler) {
  if (handler == null) {
    setMockMessageHandler(, null);

  final StreamController<Object?> controller = StreamController<Object?>();

  setMockMethodCallHandler(MethodChannel(, channel.codec), (MethodCall call) async {
    switch (call.method) {
      case 'listen':
        return handler.onListen(call.arguments, MockStreamHandlerEventSink(controller.sink));
      case 'cancel':
        return handler.onCancel(call.arguments);
        throw UnimplementedError('Method ${call.method} not implemented');

  final StreamSubscription<Object?> sub =
    (Object? e) => handlePlatformMessage(,
  sub.onError((Object? e) {
    if (e is! PlatformException) {
      throw ArgumentError('Stream error must be a PlatformException');
        code: e.code,
        message: e.message,
        details: e.details,
  sub.onDone(() => handlePlatformMessage(, null, null));