setMockDecodedMessageHandler<T> method Null safety

void setMockDecodedMessageHandler<T>(
  1. BasicMessageChannel<T> channel,
  2. Future<T> handler(
    1. T? message
    )?
)

Set a callback for intercepting messages sent to the platform on the given channel.

Intercepted messages are not forwarded to the platform.

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

Messages are decoded using the codec of the channel.

The handler's return value, if non-null, is used as a response, after encoding it using the channel's codec.

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 callbacks are cleared after each test.

See also:

Implementation

void setMockDecodedMessageHandler<T>(BasicMessageChannel<T> channel, Future<T> Function(T? message)? handler) {
  if (handler == null) {
    setMockMessageHandler(channel.name, null);
    return;
  }
  setMockMessageHandler(channel.name, (ByteData? message) async {
    return channel.codec.encodeMessage(await handler(channel.codec.decodeMessage(message)));
  }, handler);
}