writeHostApi method

  1. @override
void writeHostApi(
  1. SwiftOptions generatorOptions,
  2. Root root,
  3. Indent indent,
  4. AstHostApi api, {
  5. required String dartPackageName,
})
override

Write the swift code that represents a host Api, api. Example: protocol Foo { Int32 add(x: Int32, y: Int32) }

Implementation

@override
void writeHostApi(
  SwiftOptions generatorOptions,
  Root root,
  Indent indent,
  AstHostApi api, {
  required String dartPackageName,
}) {
  final String apiName = api.name;

  final bool isCustomCodec = getCodecClasses(api, root).isNotEmpty;
  if (isCustomCodec) {
    _writeCodec(indent, api, root);
  }
  const List<String> generatedComments = <String>[
    ' Generated protocol from Pigeon that represents a handler of messages from Flutter.'
  ];
  addDocumentationComments(indent, api.documentationComments, _docCommentSpec,
      generatorComments: generatedComments);

  indent.write('protocol $apiName ');
  indent.addScoped('{', '}', () {
    for (final Method method in api.methods) {
      addDocumentationComments(
          indent, method.documentationComments, _docCommentSpec);
      indent.writeln(_getMethodSignature(
        name: method.name,
        parameters: method.parameters,
        returnType: method.returnType,
        errorTypeName: 'Error',
        isAsynchronous: method.isAsynchronous,
        swiftFunction: method.swiftFunction,
      ));
    }
  });

  indent.newln();
  indent.writeln(
      '$_docCommentPrefix Generated setup class from Pigeon to handle messages through the `binaryMessenger`.');
  indent.write('class ${apiName}Setup ');
  indent.addScoped('{', '}', () {
    final String codecName = _getCodecName(api);
    indent.writeln('$_docCommentPrefix The codec used by $apiName.');
    String codecArgumentString = '';
    if (getCodecClasses(api, root).isNotEmpty) {
      codecArgumentString = ', codec: codec';
      indent.writeln(
          'static var codec: FlutterStandardMessageCodec { $codecName.shared }');
    }
    indent.writeln(
        '$_docCommentPrefix Sets up an instance of `$apiName` to handle messages through the `binaryMessenger`.');
    indent.write(
        'static func setUp(binaryMessenger: FlutterBinaryMessenger, api: $apiName?, messageChannelSuffix: String = "") ');
    indent.addScoped('{', '}', () {
      indent.writeln(
          r'let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : ""');
      for (final Method method in api.methods) {
        _writeHostMethodMessageHandler(
          indent,
          name: method.name,
          channelName: makeChannelName(api, method, dartPackageName),
          parameters: method.parameters,
          returnType: method.returnType,
          isAsynchronous: method.isAsynchronous,
          codecArgumentString: codecArgumentString,
          swiftFunction: method.swiftFunction,
          documentationComments: method.documentationComments,
        );
      }
    });
  });
}