pickVariants method

  1. @visibleForTesting
Style pickVariants(
  1. List<IVariant> pickedVariants, {
  2. bool isRecursive = false,
})

Picks and applies only the attributes within the specified Variant instances, and returns a new Style.

Unlike applyVariants, pickVariants ignores all other attributes initially present in the Style.

If the list of pickVariants is empty, returns a new empty Style.

Example:

final outlinedVariant = Variant('outlined');
final smallVariant = Variant('small');
final style = Style(attr1, attr2, outlinedVariant(buttonAttr1, buttonAttr2), smallVariant(buttonAttr3));
final pickedMix = style.pickVariants([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 pickVariants method is called on the Style instance with a list of outlinedVariant and smallVariant as the argument.
  • The pickVariants method returns a new Style instance pickedMix with only the attributes of the selected variants, ignoring attr1 and attr2.
  • The resulting pickedMix is equivalent to Style(buttonAttr1, buttonAttr2, buttonAttr3).

Note: The attributes attr1 and attr2 from the initial Style are ignored, and only the attributes within the specified variants are picked and applied to the new Style.

Implementation

@visibleForTesting
Style pickVariants(
  List<IVariant> pickedVariants, {
  bool isRecursive = false,
}) {
  final matchedVariants = <VariantAttribute>[];

  // Return an empty Style if the list of picked variants is empty

  for (final variantAttr in variants.values) {
    if (pickedVariants.contains(variantAttr.variant)) {
      matchedVariants.add(variantAttr);
    }
  }
  if (pickedVariants.isEmpty || matchedVariants.isEmpty) {
    return isRecursive ? this : const Style.empty();
  }

  final pickedStyle = Style.combine(matchedVariants.map((e) => e.value));

  return pickedStyle.pickVariants(pickedVariants, isRecursive: true);
}