style function

String style(
  1. Object input, [
  2. ConsoleTextStyle? style,
  3. bool reset = true
])

Apply a ConsoleTextStyle to a string.

Parameters:

  • input: The string to apply the style to.
  • style: The style to apply to the string.
  • reset: Whether to reset the style to the previous style after the string. When colors are reset, they will always be set back to the consoles default color instead of the previous style color. Defaults to true.

Implementation

String style(Object input, [ConsoleTextStyle? style, bool reset = true]) {
  if (style == null) {
    return input.toString();
  }

  String ansiStart = "\u001b[${<int>[
    if (style.color != null) ..._colorToAnsiCode(style.color!),
    if (style.backgroundColor != null)
      ..._colorToAnsiCode(style.backgroundColor!, background: true),
    ...style.parametersToEnable.map((e) => e.ansiCode),
    ...style.parametersToDisable.map((e) => e.ansiResetCode),
  ].join(';')}m";

  String result = ansiStart + input.toString();

  if (reset) {
    String ansiEnd = "\u001b[${<int>[
      if (style.color != null) ConsoleColor.reset.ansiCode,
      if (style.backgroundColor != null) ConsoleColor.reset.ansiCodeBackground,
      ...style.parametersToEnable.map((e) => e.ansiResetCode),
      ...style.parametersToDisable.map((e) => e.ansiCode),
    ].join(';')}m";

    result += ansiEnd;
  }

  return result;
}