function_plotter.dart 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // tools/function_plotter.dart
  2. import 'package:flutter/material.dart';
  3. import 'package:provider/provider.dart';
  4. import '../curve_plot.dart';
  5. import '../symja.dart';
  6. /// 函数图像绘制:把一个或多个 y = f(x) 交给 Symja 采样,再用项目自己的
  7. /// [CurvePlot] 画出来。
  8. ///
  9. /// 为什么改成按钮触发的异步绘制:Symja 的求值都跑在原生侧的专用线程上,只能
  10. /// 异步拿结果;旧的 `math_expressions` 是同步的,才能每次 build 都重算一遍。
  11. /// 现在按下「绘制」采样一次,采样期间禁用按钮并显示忙碌状态。
  12. class FunctionPlotterPage extends StatefulWidget {
  13. const FunctionPlotterPage({super.key});
  14. @override
  15. State<FunctionPlotterPage> createState() => _FunctionPlotterPageState();
  16. }
  17. class _FunctionPlotterPageState extends State<FunctionPlotterPage> {
  18. /// 固定的采样区间与点数。
  19. ///
  20. /// 以前这里是用户可以填的 x/y 范围;现在横纵范围由图下面的滑动条控制,
  21. /// 输入框就用不上了。点取得密一些,放大到一小段时才有足够的点。
  22. static const double _sampleFrom = -10;
  23. static const double _sampleTo = 10;
  24. static const int _sampleCount = 800;
  25. static const int _maxCurves = 5;
  26. /// 每条曲线的固定颜色,下标与输入框一一对应(沿用旧版配色)。
  27. static const List<Color> _curveColors = <Color>[
  28. Colors.blue,
  29. Colors.red,
  30. Colors.green,
  31. Colors.orange,
  32. Colors.purple,
  33. ];
  34. final List<TextEditingController> _exprs = <TextEditingController>[
  35. TextEditingController(text: 'x^2'),
  36. ];
  37. List<CurveSeries> _series = const <CurveSeries>[];
  38. /// 每个输入框的错误信息,与 [_exprs] 下标对齐;null 表示该项正常。
  39. List<String?> _errors = const <String?>[];
  40. /// 坐标范围本身的错误(与某条曲线无关),显示在绘图区。
  41. bool _busy = false;
  42. @override
  43. void initState() {
  44. super.initState();
  45. // 首帧后再绘制:context.read 需要 element 已经挂载到 Provider 之下。
  46. WidgetsBinding.instance.addPostFrameCallback((_) => _plot());
  47. }
  48. @override
  49. void dispose() {
  50. for (final c in _exprs) {
  51. c.dispose();
  52. }
  53. super.dispose();
  54. }
  55. void _addCurve() {
  56. if (_exprs.length >= _maxCurves) return;
  57. setState(() => _exprs.add(TextEditingController()));
  58. }
  59. void _removeCurve(int index) {
  60. if (_exprs.length <= 1) return;
  61. setState(() => _exprs.removeAt(index).dispose());
  62. }
  63. Future<void> _plot() async {
  64. if (_busy) return;
  65. final session = context.read<SymjaSession>();
  66. setState(() {
  67. _busy = true;
  68. // 每次重绘都重建,长度与输入框对齐,旧错误自然被清掉。
  69. _errors = List<String?>.filled(_exprs.length, null);
  70. });
  71. final result = <CurveSeries>[];
  72. // 逐条采样:一条失败不影响其它条,错误只挂到它自己那一栏。
  73. for (var i = 0; i < _exprs.length; i++) {
  74. final raw = _exprs[i].text.trim();
  75. if (raw.isEmpty) continue;
  76. try {
  77. // 表达式**原样交给 Symja 解析** —— 不再自己转换,谁解析谁负责,
  78. // 免得"工具里算得出来、控制台里又不对"。
  79. final expr = raw;
  80. // 采样区间固定,不再由输入框决定 —— 横纵范围交给图下面的滑动条。
  81. // 点取得密一些(800 个),这样放大到一小段时也还有足够的点。
  82. final s = await session.sample(
  83. expr,
  84. variable: 'x',
  85. from: _sampleFrom,
  86. to: _sampleTo,
  87. count: _sampleCount,
  88. );
  89. if (!mounted) return;
  90. result.add(CurveSeries(
  91. label: raw,
  92. color: _curveColors[i],
  93. // 非有限值(极点处的 ComplexInfinity 等)原样保留,
  94. // CurvePlot 会把它们当成抬笔断点,这里不做过滤。
  95. points: <Offset>[
  96. for (var k = 0; k < s.ys.length; k++) Offset(s.xAt(k), s.ys[k]),
  97. ],
  98. ));
  99. } on SymjaException catch (e) {
  100. if (!mounted) return;
  101. _errors[i] = '$e';
  102. }
  103. }
  104. if (!mounted) return;
  105. setState(() {
  106. _series = result;
  107. _busy = false;
  108. });
  109. }
  110. @override
  111. Widget build(BuildContext context) {
  112. return Scaffold(
  113. appBar: AppBar(
  114. title: const Text('函数图像绘制', style: TextStyle(color: Colors.black)),
  115. backgroundColor: Colors.white,
  116. elevation: 1,
  117. actions: [
  118. IconButton(
  119. icon: const Icon(Icons.refresh),
  120. onPressed: _busy ? null : _plot,
  121. tooltip: '重新绘制',
  122. ),
  123. ],
  124. ),
  125. body: SingleChildScrollView(
  126. child: Padding(
  127. padding: const EdgeInsets.all(16),
  128. child: Column(
  129. children: [
  130. _buildInputs(),
  131. const SizedBox(height: 16),
  132. SizedBox(
  133. height: MediaQuery.of(context).size.height * 0.5,
  134. child: _buildPlotArea(),
  135. ),
  136. ],
  137. ),
  138. ),
  139. ),
  140. );
  141. }
  142. Widget _buildInputs() {
  143. return Card(
  144. elevation: 4,
  145. child: Padding(
  146. padding: const EdgeInsets.all(16),
  147. child: Column(
  148. crossAxisAlignment: CrossAxisAlignment.start,
  149. children: [
  150. const Text(
  151. '函数表达式 (使用 x 作为变量)',
  152. style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
  153. ),
  154. const SizedBox(height: 10),
  155. const Text(
  156. '支持: +, -, *, /, ^, sin, cos, tan, ln, sqrt, pi, e',
  157. style: TextStyle(fontSize: 12, color: Colors.grey),
  158. ),
  159. const SizedBox(height: 10),
  160. const SizedBox(height: 10),
  161. Container(
  162. constraints: const BoxConstraints(maxHeight: 240),
  163. child: ListView.builder(
  164. shrinkWrap: true,
  165. itemCount: _exprs.length,
  166. itemBuilder: _buildExprRow,
  167. ),
  168. ),
  169. const SizedBox(height: 10),
  170. Row(
  171. children: [
  172. if (_exprs.length < _maxCurves)
  173. OutlinedButton.icon(
  174. onPressed: _busy ? null : _addCurve,
  175. icon: const Icon(Icons.add),
  176. label: const Text('添加函数'),
  177. ),
  178. const Spacer(),
  179. ElevatedButton.icon(
  180. onPressed: _busy ? null : _plot,
  181. icon: _busy
  182. ? const SizedBox(
  183. width: 16,
  184. height: 16,
  185. child: CircularProgressIndicator(strokeWidth: 2),
  186. )
  187. : const Icon(Icons.show_chart),
  188. label: Text(_busy ? '绘制中…' : '绘制图像'),
  189. style: ElevatedButton.styleFrom(
  190. backgroundColor: Colors.blue,
  191. foregroundColor: Colors.white,
  192. ),
  193. ),
  194. ],
  195. ),
  196. ],
  197. ),
  198. ),
  199. );
  200. }
  201. Widget _buildExprRow(BuildContext context, int index) {
  202. return Padding(
  203. padding: const EdgeInsets.symmetric(vertical: 5),
  204. child: Row(
  205. crossAxisAlignment: CrossAxisAlignment.start,
  206. children: [
  207. Container(
  208. width: 20,
  209. height: 20,
  210. margin: const EdgeInsets.only(top: 16),
  211. decoration: BoxDecoration(
  212. color: _curveColors[index],
  213. shape: BoxShape.circle,
  214. ),
  215. ),
  216. const SizedBox(width: 10),
  217. Expanded(
  218. child: Column(
  219. crossAxisAlignment: CrossAxisAlignment.start,
  220. children: [
  221. TextField(
  222. controller: _exprs[index],
  223. decoration: InputDecoration(
  224. hintText: '例如: x^2, Sin[x], Sqrt[x], Exp[x]',
  225. border: const OutlineInputBorder(),
  226. errorText: index < _errors.length ? _errors[index] : null,
  227. ),
  228. ),
  229. ],
  230. ),
  231. ),
  232. const SizedBox(width: 10),
  233. if (_exprs.length > 1)
  234. IconButton(
  235. icon: const Icon(Icons.remove, color: Colors.red),
  236. tooltip: '删除该函数',
  237. onPressed: () => _removeCurve(index),
  238. ),
  239. ],
  240. ),
  241. );
  242. }
  243. Widget _buildPlotArea() {
  244. return Card(
  245. elevation: 4,
  246. child: Padding(
  247. padding: const EdgeInsets.all(16),
  248. child: Column(
  249. children: [
  250. const Text(
  251. '函数图像',
  252. style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
  253. ),
  254. const SizedBox(height: 10),
  255. Expanded(child: _buildPlot()),
  256. ],
  257. ),
  258. ),
  259. );
  260. }
  261. Widget _buildPlot() {
  262. if (_busy) {
  263. return const Center(child: CircularProgressIndicator());
  264. }
  265. if (_series.isEmpty) {
  266. return Center(
  267. child: Column(
  268. mainAxisAlignment: MainAxisAlignment.center,
  269. children: const [
  270. Icon(Icons.functions, size: 50, color: Colors.grey),
  271. SizedBox(height: 10),
  272. Text('暂无函数图像可显示', style: TextStyle(color: Colors.grey)),
  273. Text(
  274. '请输入函数表达式后点击「绘制图像」',
  275. style: TextStyle(color: Colors.grey, fontSize: 12),
  276. ),
  277. ],
  278. ),
  279. );
  280. }
  281. return CurvePlot(series: _series);
  282. }
  283. }