ensureLibraryComponentReuse method

void ensureLibraryComponentReuse({
  1. required String page,
  2. required BrownfieldPatternTarget anchor,
  3. required String libraryProjectId,
  4. required String componentName,
  5. required String componentKey,
  6. required Map<String, DslType> params,
  7. Map<String, Object?> arguments = const <String, Object?>{},
  8. String? insertedName,
  9. bool after = true,
})

Inserts a linked library component beside an existing anchor.

The linked library dependency must already be present on the project.

Example:

app.ensureLibraryComponentReuse(
  page: 'HomePage',
  anchor: BrownfieldPatternTarget.byName('PromoSection'),
  libraryProjectId: 'shared-kit-project',
  componentName: 'PromoCard',
  componentKey: 'Container_xxdmnqyy',
  params: {'title': string},
  arguments: {'title': 'Spring launch'},
);

Implementation

void ensureLibraryComponentReuse({
  required String page,
  required BrownfieldPatternTarget anchor,
  required String libraryProjectId,
  required String componentName,
  required String componentKey,
  required Map<String, DslType> params,
  Map<String, Object?> arguments = const <String, Object?>{},
  String? insertedName,
  bool after = true,
}) {
  raw((project) {
    final hasDependency = project.dependencies.any(
      (dependency) => dependency.projectId == libraryProjectId,
    );
    if (!hasDependency) {
      throw StateError(
        'Library dependency "$libraryProjectId" was not found for reuse.',
      );
    }
    final editor = _pagePatternEditor(page);
    final snapshot = _requirePagePatternSnapshot(project, page);
    final anchorRef = _resolvePatternTarget(
      snapshot,
      editor,
      anchor,
      operation: 'ensureLibraryComponentReuse(anchor: ...)',
    );
    final handle = LibraryComponentHandle(
      name: componentName,
      libraryProjectId: libraryProjectId,
      componentKey: componentKey,
      params: params,
    );
    final instance = ComponentInstance(
      component: handle,
      name: insertedName ?? componentName,
      arguments: arguments,
    );
    if (after) {
      editor.ensureInsertedAfter(
        _selectionForResolvedTarget(editor, anchorRef),
        instance,
      );
    } else {
      editor.ensureInsertedBefore(
        _selectionForResolvedTarget(editor, anchorRef),
        instance,
      );
    }
    _applyBrownfieldWidgetClassEdit(project, editor);
  });
}