Flutter_widget_from_html: Add support for inline math equations via Katex or similar

Created on 4 May 2020  路  9Comments  路  Source: daohoangson/flutter_widget_from_html

Please add support for inline math equations via Katex or similar if possible in the future

enhancement help wanted

All 9 comments

This package looks promising https://pub.dev/packages/flutter_tex

+1
When data fetched from server with Latex code encoded in $...$ or something like that, if it can render that, it would have been more than awesome.

@imarindam do you have sample HTML?

@daohoangson There you go:

<p>$T_{r+1}=\,^{5}C_{r}(2a)^{r}\left ( \frac{2}{a} \right )^{5-r}$</p>
<p>$=\,^{5}C_{r}\,(2)^{r}\, (a)^{r}\,(2)^{5-r}\,(a)^{r-5}$</p>
<p>$=\,^{5}C_{r}\,(2)^{5}\, (a)^{2r-5}$</p>
<p>For 2nd term $r=2$</p>
<p>$\therefore T_{2+1} =\,^{5}C_{2}\,(2)^{5}$</p>
<p>$=\frac{5\,!}{2\,! \times 3\,!} \times 2^{5}$</p>
<p>$=\frac{5 \times 4 \times \times 3\,!}{2\,! \times 3\,!} \times 32$</p>
<p>$=5 \times 2 \times 32$</p>
<p>$=320$</p>

It should look like this.

How does a normal webpage know to render this markup as latex? They have some special JavaScript that detects $ or something? Hey @imarindam do you have link to a webpage that uses this type of markup?

Just to let you know, I've implemented this library in my HTML widgets. Here's how (but I'm pretty sure there exists some other better methods) :

  1. I process the input string by putting math formulas $2+2 = 4$ inside a __ html tag <math>2+2 = 4</math> (using this regex : input.replaceAllMapped(RegExp(r'(\$+)(?:(?!\1)[\s\S])*\1'), (match) => '<math>${removeTrailingAndLeadingDollars(match.group(0))}</math>').
  2. I render the math tag using a custom Widget Factory :
@override
void parse(BuildMetadata meta) {
  super.parse(meta);
  if (meta.element.localName == 'math') {
    math ??= BuildOp(
      onTree: (meta, tree) => tree.replaceWith(
        WidgetBit.inline(
          tree,
          Math.tex(
            meta.element.text,
            textStyle: textStyle,
            mathStyle: MathStyle.text,
          ),
        ),
      ),
    );
    meta.register(math);
  }
}
  1. That's all.

but I'm pretty sure there exists some other better methods

I think you did it beautifully. Personally I always try to avoid regex because of all the corner cases but in this instance, I don't think I can do any better than yours.

@daohoangson Cool then, hope it can be useful for you (or for anyone viewing this issue).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ahmadkhedr picture ahmadkhedr  路  6Comments

ahmadkhedr picture ahmadkhedr  路  6Comments

SoFo12 picture SoFo12  路  4Comments

leewonghao picture leewonghao  路  7Comments

forever84721 picture forever84721  路  4Comments