combineAttrs function

Attrs combineAttrs(
  1. Attrs source,
  2. Attrs target
)

Combine source attributes into target, merging class and style values.

When both source and target have a 'class' attribute, they are combined with a space. When both have a 'style' attribute, they are combined with a semicolon. Other attributes from source override target.

Returns the modified target map.

final target = {'class': 'foo', 'id': 'bar'};
combineAttrs({'class': 'baz', 'data-x': '1'}, target);
// Result: {'class': 'foo baz', 'id': 'bar', 'data-x': '1'}

Implementation

Attrs combineAttrs(Attrs source, Attrs target) {
  for (final entry in source.entries) {
    final name = entry.key;
    final value = entry.value;

    if (name == 'class' && target.containsKey('class')) {
      target['class'] = '${target['class']} $value';
    } else if (name == 'style' && target.containsKey('style')) {
      target['style'] = '${target['style']};$value';
    } else {
      target[name] = value;
    }
  }
  return target;
}