applyVariants method
Selects multiple Variant instances and returns a new Style with the selected variants.
If the applyVariants list is empty, returns this mix without any changes.
Otherwise, the method merges the attributes of the selected variants into a new Style instance.
Example:
final outlinedVariant = Variant('outlined');
final smallVariant = Variant('small');
final style = Style(
attr1,
attr2,
outlinedVariant(attr3, attr4),
smallVariant(attr5),
);
final outlinedSmallMix = style.applyVariants(outlinedVariant, smallVariant);
In this example:
- Two `Variant` instances `outlinedVariant` and `smallVariant` are created.
- An initial `Style` instance `style` is created with `attr1` and `attr2`, along with the two variants.
- The `applyVariants` method is called on the `Style` instance with a list of `outlinedVariant` and `smallVariant` as the argument.
- The `applyVariants` method returns a new `Style` instance `outlinedSmallMix` with the attributes of the selected variants merged.
- The resulting `outlinedSmallMix` is equivalent to `Style(attr1, attr2, attr3, attr4, attr5)`.
Note:
The attributes from the selected variants (`attr3`, `attr4`, and `attr5`) are not applied to the `Style` instance until the `applyVariants` method is called.
Implementation
Style applyVariants(List<Variant> selectedVariants) {
/// Return the original Style if no variants were selected
if (selectedVariants.isEmpty) {
return this;
}
/// Initializing two empty lists that store the matched and remaining `Variants`, respectively.
final matchedVariants = <VariantAttribute>[];
final remainingVariants = <VariantAttribute>[];
/// Loop over all VariantAttributes in variants only once instead of a nested loop,
/// checking if each one matches with the selected variants.
/// If it does, add it to the matchedVariants, else add it to remainingVariants.
for (final variant in variants.values) {
if (variant.matches(selectedVariants)) {
matchedVariants.add(variant);
} else {
final remainingVariant = variant.removeVariants(selectedVariants);
if (remainingVariant != null) {
remainingVariants.add(remainingVariant);
}
}
}
final updatedStyle = Style._(
styles: styles,
variants: AttributeMap(remainingVariants),
);
/// If not a single variant was matched, return the original Style.
if (matchedVariants.isEmpty) {
return updatedStyle;
}
/// Create a Style from the matched variants.
final styleToApply =
Style.combine(matchedVariants.map((e) => e.value).toList());
/// Merge the new Style created with the existing Style, excluding the matched variants.
final mergedStyle = updatedStyle.merge(styleToApply);
/// Apply all variants and return the final Style.
return mergedStyle.applyVariants(selectedVariants);
}