toggleAttribute method

bool toggleAttribute(
  1. TextAttribute attribute
)

Toggle an attribute for the current selection.

For a collapsed selection, if an attribute would normally be applied on insertion, a call to this method makes it so the attribute is not applied and vice-versa. I.e. the result of isApplied will be inverted for attribute after calling this method. This will only have an effect if the attribute's end rule is set to ExpandRule.inclusive.

For a range selection, if the attribute is not applied to the full selection it will be applied to the full selection. Otherwise the attribute will be removed from the selection.

This method uses setOverride to temporarily override what attributes will be applied for collapsed selections.

Implementation

bool toggleAttribute(
  TextAttribute attribute,
) {
  final applied = isApplied(attribute);
  if (selection.isCollapsed &&
      attribute.expandRules.end == ExpandRule.inclusive) {
    final overrideType = applied ? OverrideType.remove : OverrideType.apply;
    setOverride(attribute, overrideType);
  } else {
    if (applied) {
      spans = spans.removeFrom(_convertRange(selection), attribute);
    } else {
      applyAttribute(attribute);
    }
  }

  return !applied;
}