Component.apply constructor
const
Component.apply({})
Creates a component which applies id, classes, styles, attributes, and events
to the elements of child that target matches.
This does not render an element itself.
By default, target is ApplyTarget.anyChild,
which matches the top-level elements of child.
The classes are added to each matched element's classes.
The id and each style, attribute, and event only apply where neither
the element nor a Component.apply nested in this one already sets them.
On the client, this also applies to the server-rendered elements of a server component, such as a component passed to a @client component.
Precedence and Merging Rules
- Precedence: Target-owned properties always take precedence over applied properties. Inner Component.apply wrappers also take precedence over outer ones.
- Classes: Applied
classesare merged as a set of whitespace-separated tokens with the target's classes. If the target element specifies raw class names viaattributes: {'class': ...}, classes from Component.apply are never applied to that element to preserve raw attributes and prevent duplicate HTML attributes. - Styles: Applied
stylesare merged on a per-property basis. Any style property already defined on the target element is preserved. If a target element specifies raw inline styles viaattributes: {'style': ...}, styles from Component.apply are never applied to that element to avoid corrupting raw style declarations or unsafe mixing of structured and raw styles. - ID & Attributes: An
idor other attributes defined on the target element (or in its attributes map) are never overwritten by applied values. - Events: Event listeners on the target element take precedence; applied listeners are added as supplementary listeners if not already bound.
Example:
return Component.apply(
target: ApplyTarget.anyChild,
classes: 'applied-class',
styles: Styles(backgroundColor: Colors.blue, padding: Padding.all(8.px)),
child: Component.element(
tag: 'div',
classes: 'some-class',
styles: Styles(backgroundColor: Colors.red),
children: [
Component.text('Hello World'),
],
),
);
Renders:
<div class="some-class applied-class" style="background-color: red; padding: 8px">
Hello World
</div>
Implementation
const factory Component.apply({
ApplyTarget target,
String? id,
String? classes,
Styles? styles,
Map<String, String>? attributes,
Map<String, EventCallback>? events,
required Component child,
Key? key,
}) = ApplyDomComponent;