toggleAttribute method

Future<void> toggleAttribute(
  1. String key, {
  2. Selection? selection,
  3. Map? selectionExtraInfo,
})

Toggles the given attribute on or off for the selected text.

If the Selection is not passed in, use the current selection.

Implementation

Future<void> toggleAttribute(
  String key, {
  Selection? selection,
  Map? selectionExtraInfo,
}) async {
  selection ??= this.selection;
  if (selection == null) {
    return;
  }

  final nodes = getNodesInSelection(selection);
  if (selection.isCollapsed) {
    if (toggledStyle.containsKey(key)) {
      updateToggledStyle(key, !toggledStyle[key]!);
    } else {
      // get the attributes from the previous one character.
      selection = selection.copyWith(
        start: selection.start.copyWith(
          offset: max(
            selection.startIndex - 1,
            0,
          ),
        ),
      );
      final toggled = nodes.allSatisfyInSelection(selection, (delta) {
        return delta.everyAttributes(
          (attributes) => attributes[key] == true,
        );
      });
      updateToggledStyle(key, !toggled);
    }
  } else {
    final isHighlight = nodes.allSatisfyInSelection(selection, (delta) {
      return delta.everyAttributes(
        (attributes) => attributes[key] == true,
      );
    });
    await formatDelta(
      selection,
      {
        key: !isHighlight,
      },
      selectionExtraInfo: selectionExtraInfo,
    );
  }
}