RichInputValue.fromHtml constructor

RichInputValue.fromHtml(
  1. String html,
  2. TextStyle defaultTextStyle
)

Supported tag , ,

Implementation

factory RichInputValue.fromHtml(String html, TextStyle defaultTextStyle) {
  Map<int, TextStyle> styles = {};
  String text = '';

  TextStyle currentTextStyle = defaultTextStyle;

  for (int i = 0; i < html.length; i++) {
    if (html[i] == '<') {
      bool toggleOn = true;
      int offset = 0;

      if (html[i + 1] == '/') {
        toggleOn = false;
        offset = 1;
      }

      switch (html[i + 1 + offset]) {
        case 'b':
          if (html[i + 2 + offset] == '>') {
            currentTextStyle = currentTextStyle.copyWith(fontWeight: toggleOn ? FontWeight.w700 : defaultTextStyle.fontWeight);
            i += 3 + offset;
          } else if (html[i + 2 + offset] == 'r' && html[i + 3 + offset] == '>') {
            text = text + '\n';
            i += 3 + offset;
            continue;
          }
          break;
        case 'i':
          currentTextStyle = currentTextStyle.copyWith(fontStyle: toggleOn ? FontStyle.italic : defaultTextStyle.fontStyle);
          i += 3 + offset;
          break;
        case 'u':
          currentTextStyle = currentTextStyle.copyWith(decoration: toggleOn ? TextDecoration.underline : defaultTextStyle.decoration);
          i += 3 + offset;
          break;
      }
    }

    if (i >= html.length) break;
    if (html[i] == '<') {
      i--;
      continue;
    }

    text += html[i];
    styles[text.length - 1] = currentTextStyle;
  }

  return RichInputValue(
    text: text,
    styles: styles,
    defaultTextStyle: defaultTextStyle,
  );
}