setMockMethodCallHandler method

void setMockMethodCallHandler(
  1. MethodChannel channel,
  2. Future<Object?>? handler(
    1. MethodCall message
    )?
)

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

Intercepted method calls 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.

Methods are decoded using the codec of the channel.

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

To send an error, throw a PlatformException in the handler. Other exceptions are not caught.

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 setMockMethodCallHandler(MethodChannel channel, Future<Object?>? Function(MethodCall message)? handler) {
  if (handler == null) {
    setMockMessageHandler(channel.name, null);
    return;
  }
  setMockMessageHandler(channel.name, (ByteData? message) async {
    final MethodCall call = channel.codec.decodeMethodCall(message);
    try {
      return channel.codec.encodeSuccessEnvelope(await handler(call));
    } on PlatformException catch (error) {
      return channel.codec.encodeErrorEnvelope(
        code: error.code,
        message: error.message,
        details: error.details,
      );
    } on MissingPluginException {
      return null;
    } catch (error) {
      return channel.codec.encodeErrorEnvelope(code: 'error', message: '$error');
    }
  }, handler);
}