MarkdownParser constructor Null safety

MarkdownParser(
  1. String data
)

Implementation

MarkdownParser(this.data) {
  plainText = '';
  spans = [MarkdownSpan(text: '', markups: [], style: TextStyle())];

  bool bold = false;
  bool italic = false;
  bool underline = false;

  const String MARKUP_BOLD = '**';
  const String MARKUP_ITALIC = '_';
  const String MARKUP_UNDERLINE = '++';

  addSpan(String markup, bool isOpening) {
    final List<Markup> markups = [Markup(markup, isOpening)];

    if (bold && markup != MARKUP_BOLD) markups.add(Markup(MARKUP_BOLD, true));
    if (italic && markup != MARKUP_ITALIC)
      markups.add(Markup(MARKUP_ITALIC, true));
    if (underline && markup != MARKUP_UNDERLINE)
      markups.add(Markup(MARKUP_UNDERLINE, true));

    spans.add(
      MarkdownSpan(
        text: '',
        markups: markups,
        style: TextStyle(
          fontWeight: bold ? FontWeight.bold : null,
          fontStyle: italic ? FontStyle.italic : null,
          decoration: underline ? TextDecoration.underline : null,
        ),
      ),
    );
  }

  bool checkMarkup(int i, String markup) {
    return data.substring(i, min(i + markup.length, data.length)) == markup;
  }

  for (int c = 0; c < data.length; c++) {
    if (checkMarkup(c, MARKUP_BOLD)) {
      bold = !bold;
      addSpan(MARKUP_BOLD, bold);
      c += MARKUP_BOLD.length - 1;
    } else if (checkMarkup(c, MARKUP_ITALIC)) {
      italic = !italic;
      addSpan(MARKUP_ITALIC, italic);
      c += MARKUP_ITALIC.length - 1;
    } else if (checkMarkup(c, MARKUP_UNDERLINE)) {
      underline = !underline;
      addSpan(MARKUP_UNDERLINE, underline);
      c += MARKUP_UNDERLINE.length - 1;
    } else {
      spans[spans.length - 1].text += data[c];
      plainText = plainText ?? "" + data[c];
    }
  }
}