registerBoolServiceExtension method

  1. @protected
void registerBoolServiceExtension ({@required String name, @required AsyncValueGetter<bool> getter, @required AsyncValueSetter<bool> setter })
@protected

Registers a service extension method with the given name (full name "ext.flutter.name"), which takes a single argument "enabled" which can have the value "true" or the value "false" or can be omitted to read the current value. (Any value other than "true" is considered equivalent to "false". Other arguments are ignored.)

Calls the getter callback to obtain the value when responding to the service extension method being called.

Calls the setter callback with the new value when the service extension method is called with a new value.

A registered service extension can only be activated if the vm-service is included in the build, which only happens in debug and profile mode. Although a service extension cannot be used in release mode its code may still be included in the Dart snapshot and blow up binary size if it is not wrapped in a guard that allows the tree shaker to remove it (see sample code below).

{@inject-html}

{@end-inject-html}The following code registers a service extension that is only included in debug builds.{@inject-html}
void myRegistrationFunction() {
  assert(() {
    // Register your service extension here.
    return true;
  }());
}
{@end-inject-html}

{@inject-html}

{@end-inject-html}A service extension registered with the following code snippet is available in debug and profile mode.{@inject-html}
void myRegistrationFunction() {
  // kReleaseMode is defined in the 'flutter/foundation.dart' package.
  if (!kReleaseMode) {
    // Register your service extension here.
  }
}
{@end-inject-html}

Both guards ensure that Dart's tree shaker can remove the code for the service extension in release builds.

Implementation

@protected
void registerBoolServiceExtension({
  @required String name,
  @required AsyncValueGetter<bool> getter,
  @required AsyncValueSetter<bool> setter,
}) {
  assert(name != null);
  assert(getter != null);
  assert(setter != null);
  registerServiceExtension(
    name: name,
    callback: (Map<String, String> parameters) async {
      if (parameters.containsKey('enabled')) {
        await setter(parameters['enabled'] == 'true');
        _postExtensionStateChangedEvent(name, await getter() ? 'true' : 'false');
      }
      return <String, dynamic>{'enabled': await getter() ? 'true' : 'false'};
    },
  );
}