How to show html containing mathjax without using webview

92 Views Asked by At

<p>যদি \(\mathrm{a+b=\sqrt{5}}\) এবং \(\mathrm{a-b=\sqrt{3}}\) হয়, তবে \(\mathrm{a^2+b^2=}\) কত?</p>

I have about 100 strings like the above html string. I want to show this in flutter. I used flutter_tex package and it worked but since it uses webview it slow down the performance. flutter_tex takes so much time to render the string in webview. So for improving performance I want to avoid webview.

I read the flutter_html package documentation and guessed that it is possible using this but can't make the right code.

Here is a sample code taken from their documentation.

`Widget htmlWidget = Html(
data: r"""<tex>i\hbar\frac{\partial}{\partial t}\Psi(\vec x,t) = -\frac{\hbar}        {2m}\nabla^2\Psi(\vec x,t)+ V(\vec x)\Psi(\vec x,t)</tex>""",
customRender: {
"tex": (RenderContext context, _) => Math.tex(
context.tree.element!.text,
onErrorFallback: (FlutterMathException e) {
//return your error widget here e.g.
return Text(e.message);
},
),
},
tagsList: Html.tags..add('tex'),
);`

I am new in flutter. Can you help me to make the equivalent code for my provided above html string?

Thanks in advance.

I am trying with flutter_tex and it worked but very slow since it uses webview and I have many string so it make many webview at a time. I want a solution without webview.

1

There are 1 best solutions below

5
Dhafin Rayhan On

As shown in the readme, the flutter_html package requires flutter_math plugin to render TeX. The flutter_math package is currently unmaintained, so you can use flutter_math_fork instead.

  1. Add flutter_html and flutter_math_fork to your dependencies.
  2. Replace every math equation start (\() with <tex> and every equation end (\)) with </tex>. You can use the replaceAll method like this:
    data.replaceAll(r'\(', r'<tex>').replaceAll(r'\)', r'</tex>')
    

Use the widget like this:

Html(
  data:
      r'<p>যদি <tex>\mathrm{a+b=\sqrt{5}}</tex> এবং <tex>\mathrm{a-b=\sqrt{3}}</tex> হয়, তবে <tex>\mathrm{a^2+b^2=}</tex> কত?</p>',
  shrinkWrap: true,
  extensions: [
    TagExtension(
      tagsToExtend: {"tex"},
      builder: (extensionContext) {
        return Math.tex(
          extensionContext.innerHtml,
          textStyle: extensionContext.styledElement?.style
              .generateTextStyle(),
          onErrorFallback: (FlutterMathException e) {
            return Text(e.message);
          },
        );
      },
    ),
  ],
)