ensureProjectComponentReuse method
void
ensureProjectComponentReuse({})
Inserts an existing shared project component beside an existing anchor.
This prefers reuse over recreating an equivalent subtree.
Example:
app.ensureProjectComponentReuse(
page: 'HomePage',
anchor: BrownfieldPatternTarget.byName('HeroSection'),
componentName: 'PrimaryButton',
params: {'label': string},
arguments: {'label': 'Shop now'},
);
Implementation
void ensureProjectComponentReuse({
required String page,
required BrownfieldPatternTarget anchor,
required String componentName,
required Map<String, DslType> params,
Map<String, Object?> arguments = const <String, Object?>{},
String? insertedName,
bool after = true,
}) {
raw((project) {
final component = project_helpers.findComponent(
project,
name: componentName,
);
if (component == null) {
throw StateError(
'Project component "$componentName" was not found for reuse.',
);
}
final editor = _pagePatternEditor(page);
final snapshot = _requirePagePatternSnapshot(project, page);
final anchorRef = _resolvePatternTarget(
snapshot,
editor,
anchor,
operation: 'ensureProjectComponentReuse(anchor: ...)',
);
final handle = ExistingProjectComponentHandle(
componentName,
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);
});
}