Flutter应用中使用flutter_tex无法渲染KaTeX公式问题求助
问题:Flutter中flutter_tex无法渲染LaTeX公式,仅显示代码内容
我尝试在Flutter应用的单独标签页中添加公式,多次尝试后公式未渲染,仅显示编写的代码而非公式。我是否写错了LaTeX代码?
import 'package:flutter/material.dart'; import 'package:flutter_tex/flutter_tex.dart'; class FormulasScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Formulas'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Water Equivalent of Snow (mm)', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), SizedBox(height: 16), TeXView( child: TeXViewDocument( r''' H_{2DW}(\text{mm}) = \\frac{\text{mass of new snow (g)}}{\text{Cross-section area (cm}^2\text{)}} \\times 10 ''', ), ), // Other Formulas here ], ), ), ); } }
我已尝试使用简单公式、在线编辑器重写LaTeX代码、清理构建文件、重新构建项目及检查依赖等操作,但问题依旧。
解决方案
你的问题出在LaTeX代码的格式和转义字符使用上,以下是具体修正步骤:
- 添加公式环境标记:flutter_tex需要明确的LaTeX公式环境来识别内容,块级公式需用
$$...$$或\[...\]包裹,行内公式用$...$包裹,你的代码缺少这个标记,导致工具无法识别这是公式。 - 修正转义字符:Dart的原始字符串(
r'''...''')中,\不需要双重转义,你写的\\frac会被解析成普通的\,导致LaTeX无法识别命令,要改成\frac。
修改后的代码如下:
import 'package:flutter/material.dart'; import 'package:flutter_tex/flutter_tex.dart'; class FormulasScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Formulas'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( 'Water Equivalent of Snow (mm)', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox(height: 16), TeXView( child: TeXViewDocument( r''' $$H_{2DW}(\text{mm}) = \frac{\text{mass of new snow (g)}}{\text{Cross-section area (cm}^2\text{)}} \times 10$$ ''', ), ), // Other Formulas here ], ), ), ); } }
修改后flutter_tex就能正确识别并渲染公式了。如果仍有问题,可以先测试简单公式(比如$$E=mc^2$$)确认基础渲染正常,再逐步调整复杂公式。
内容的提问来源于stack exchange,提问作者tay-c
相关产品推荐
相关产品推荐

