setMockDecodedMessageHandler<T> method
- BasicMessageChannel<
T> channel, - Future<
T> handler(- 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 await
ing a Future will result
in the test hanging.
Registered callbacks are cleared after each test.
See also:
-
checkMockMessageHandler, which can verify if a handler is still registered, which is useful in tests to ensure that no unexpected handlers are being registered.
-
setMockMessageHandler, which is similar but provides raw access to the underlying bytes.
-
setMockMethodCallHandler, which is similar but decodes the messages using a MethodCodec.
-
setMockStreamHandler, which wraps setMockMethodCallHandler to handle EventChannel messages.
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);
}