addHookWidgetBody method

void addHookWidgetBody(
  1. void listener(
    1. FunctionBody node,
    2. AstNode diagnosticNode
    ), {
  2. bool isExactly = false,
})

Implementation

void addHookWidgetBody(
  void Function(FunctionBody node, AstNode diagnosticNode) listener, {
  bool isExactly = false,
}) {
  addInstanceCreationExpression((node) {
    final classElement = node.constructorName.type.element;
    if (classElement == null) {
      return;
    }

    final isHookBuilder = const TypeChecker.fromName(
      'HookBuilder',
      packageName: 'flutter_hooks',
    ).isExactly(classElement);
    if (!isHookBuilder) {
      return;
    }

    final builderParameter = node.argumentList.arguments
        .whereType<NamedExpression>()
        .firstWhereOrNull((e) => e.name.label.name == 'builder');
    if (builderParameter
        case NamedExpression(expression: FunctionExpression(:final body))) {
      listener(body, node.constructorName);
    }
  });
  addClassDeclaration((node) {
    final element = node.declaredElement;
    if (element == null) {
      return;
    }

    const checker = TypeChecker.fromName(
      'HookWidget',
      packageName: 'flutter_hooks',
    );

    final AstNode diagnosticNode;
    if (isExactly) {
      final superclass = node.extendsClause?.superclass;
      final superclassElement = superclass?.element;
      if (superclass == null || superclassElement == null) {
        return;
      }

      final isDirectHookWidget = checker.isExactly(superclassElement);
      if (!isDirectHookWidget) {
        return;
      }
      diagnosticNode = superclass;
    } else {
      final isHookWidget = checker.isSuperOf(element);
      if (!isHookWidget) {
        return;
      }
      diagnosticNode = node;
    }

    final buildMethod = getBuildMethod(node);
    if (buildMethod == null) {
      return;
    }

    listener(buildMethod.body, diagnosticNode);
  });
}