calculator_page.dart 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:flutter_math_fork/flutter_math.dart';
  5. import 'package:provider/provider.dart';
  6. import 'curve_plot.dart';
  7. import 'expr_editor.dart';
  8. import 'expr_node.dart';
  9. import 'expr_parse.dart';
  10. import 'symja.dart';
  11. import 'symja_functions.dart';
  12. /// 科学计算器(默认主界面)。
  13. ///
  14. /// 输入用**结构化节点树**(见 lib/expr_node.dart),不是字符串:
  15. /// 按键把节点插进当前光标槽,分数竖排、指数上标、多参数函数各有自己的槽。
  16. /// 纯文本输入留给控制台。
  17. class CalculatorPage extends StatefulWidget {
  18. const CalculatorPage({super.key});
  19. @override
  20. State<CalculatorPage> createState() => _CalculatorPageState();
  21. }
  22. class _CalculatorPageState extends State<CalculatorPage> {
  23. final _doc = ExprDoc();
  24. SymjaResult? _preview;
  25. SymjaResult? _committed;
  26. String? _error;
  27. Timer? _debounce;
  28. int _seq = 0;
  29. /// 用户点了"光标已经在的地方"—— 显示粘贴入口。
  30. bool _pastePrompt = false;
  31. @override
  32. void dispose() {
  33. _debounce?.cancel();
  34. super.dispose();
  35. }
  36. // ------------------------------------------------------------------ 求值
  37. /// 编辑器每次变化都走这里:清掉上次的提交态,防抖后重算预览。
  38. void _onDocChanged() {
  39. setState(() {
  40. _committed = null;
  41. _error = null;
  42. _pastePrompt = false; // 动过内容/光标就收起操作栏
  43. });
  44. _debounce?.cancel();
  45. _debounce = Timer(const Duration(milliseconds: 500), _runPreview);
  46. }
  47. String get _source => _doc.toSymja();
  48. void _snack(String msg) {
  49. if (!mounted) return;
  50. ScaffoldMessenger.of(context)
  51. ..hideCurrentSnackBar()
  52. ..showSnackBar(SnackBar(content: Text(msg)));
  53. }
  54. Future<void> _copy(String text, String what) async {
  55. await Clipboard.setData(ClipboardData(text: text));
  56. _snack('已复制$what:$text');
  57. }
  58. /// 从剪贴板读一段 Symja 表达式,解析成节点树后整体替换。
  59. ///
  60. /// 解析器只认一个明确的子集,**认不出来就报错**,不会猜着解析 ——
  61. /// 猜错了你会看到算错的结果,那比报错糟糕得多。
  62. Future<void> _paste() async {
  63. final data = await Clipboard.getData(Clipboard.kTextPlain);
  64. final text = (data?.text ?? '').trim();
  65. if (text.isEmpty) {
  66. _snack('剪贴板里没有文本');
  67. return;
  68. }
  69. try {
  70. final parsed = parseSymjaExpr(text);
  71. setState(() {
  72. _pastePrompt = false;
  73. if (_doc.selection != null) _doc.deleteSelection(); // 有选区就替换掉
  74. _doc.insertNodesAtCursor(parsed.children); // 否则插到光标处
  75. _preview = null;
  76. _committed = null;
  77. _error = null;
  78. });
  79. _onDocChanged();
  80. _snack('已粘贴到光标处:${_doc.toSymja()}');
  81. } on ExprParseException catch (e) {
  82. _snack('这段表达式没法转成按钮式输入 —— $e');
  83. }
  84. }
  85. // ------------------------------------------------------------------ 选区操作
  86. /// 操作栏上的图标按钮。压扁一点,别把这条栏撑高。
  87. Widget _barButton(IconData icon, String tip, VoidCallback onTap) => IconButton(
  88. tooltip: tip,
  89. icon: Icon(icon, size: 20),
  90. visualDensity: VisualDensity.compact,
  91. padding: const EdgeInsets.symmetric(horizontal: 6),
  92. constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
  93. onPressed: onTap,
  94. );
  95. Future<void> _copySelection() async {
  96. final t = _doc.selectionText;
  97. if (t.isEmpty) return;
  98. await _copy(t, '选中内容');
  99. setState(() => _doc.clearSelection());
  100. }
  101. Future<void> _cutSelection() async {
  102. final t = _doc.selectionText;
  103. if (t.isEmpty) return;
  104. await Clipboard.setData(ClipboardData(text: t));
  105. setState(() {
  106. _doc.deleteSelection();
  107. _pastePrompt = false;
  108. });
  109. _onDocChanged();
  110. _snack('已剪切:$t');
  111. }
  112. void _dismissBar() {
  113. setState(() {
  114. _pastePrompt = false;
  115. _doc.clearSelection();
  116. });
  117. }
  118. /// 选中部分内容后自动出现的操作栏;或点了光标处时的粘贴入口。
  119. Widget? _contextBar() {
  120. final sel = _doc.selection;
  121. final hasSel = sel != null && !sel.isEmpty;
  122. if (!hasSel && !_pastePrompt) return null;
  123. final scheme = Theme.of(context).colorScheme;
  124. return Material(
  125. color: scheme.surfaceContainerHighest,
  126. child: Padding(
  127. padding: const EdgeInsets.only(left: 12, right: 4),
  128. child: Row(
  129. children: [
  130. Expanded(
  131. child: Text(
  132. hasSel ? '已选中 ${_doc.selectionText}' : '粘贴到光标处',
  133. maxLines: 1,
  134. overflow: TextOverflow.ellipsis,
  135. style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
  136. ),
  137. ),
  138. // 用图标而不是文字按钮 —— 文字太占地方,一条栏塞不下几个
  139. if (hasSel) ...[
  140. _barButton(Icons.copy, '复制', _copySelection),
  141. _barButton(Icons.cut, '剪切', _cutSelection),
  142. ] else
  143. _barButton(Icons.paste, '粘贴', _paste),
  144. _barButton(Icons.close, '取消选择', _dismissBar),
  145. ],
  146. ),
  147. ),
  148. );
  149. }
  150. Future<void> _runPreview() async {
  151. final expr = _source;
  152. if (expr.isEmpty || expr == 'Null') {
  153. if (mounted) setState(() => _preview = null);
  154. return;
  155. }
  156. final session = context.read<SymjaSession>();
  157. final id = ++_seq;
  158. final r = await session.preview(expr);
  159. if (!mounted || id != _seq) return; // 已有更新的预览在路上
  160. setState(() => _preview = r);
  161. }
  162. Future<void> _commit() async {
  163. final expr = _source;
  164. if (expr.isEmpty || expr == 'Null') return;
  165. _debounce?.cancel();
  166. final session = context.read<SymjaSession>();
  167. final id = ++_seq; // 让在途的预览作废
  168. try {
  169. final r = await session.evaluate(expr);
  170. if (!mounted || id != _seq) return;
  171. setState(() {
  172. _committed = r;
  173. _preview = null;
  174. _error = null;
  175. });
  176. } on SymjaException catch (e) {
  177. if (!mounted || id != _seq) return;
  178. setState(() {
  179. _error = '$e';
  180. _committed = null;
  181. _preview = null;
  182. });
  183. }
  184. await session.refreshVariables();
  185. }
  186. Future<void> _plotCurrent() async {
  187. final expr = _source;
  188. if (expr.isEmpty || expr == 'Null') return;
  189. final session = context.read<SymjaSession>();
  190. final messenger = ScaffoldMessenger.of(context);
  191. try {
  192. final s = await session.sample(expr, from: -6.3, to: 6.3, count: 240);
  193. if (!mounted) return;
  194. await showDialog<void>(
  195. context: context,
  196. builder: (_) => AlertDialog(
  197. title: Text('$expr (${s.ys.length} 点,${s.elapsedMs} ms)'),
  198. content: SizedBox(
  199. width: 360,
  200. height: 420,
  201. child: CurvePlot(series: [
  202. CurveSeries(
  203. label: expr,
  204. color: const Color(0xFF3F51B5),
  205. points: [
  206. for (var i = 0; i < s.ys.length; i++)
  207. Offset(s.xAt(i), s.ys[i]),
  208. ],
  209. ),
  210. ]),
  211. ),
  212. actions: [
  213. TextButton(
  214. onPressed: () => Navigator.pop(context),
  215. child: const Text('关闭'),
  216. ),
  217. ],
  218. ),
  219. );
  220. } on SymjaException catch (e) {
  221. messenger.showSnackBar(SnackBar(content: Text('$e')));
  222. }
  223. }
  224. // ------------------------------------------------------------------ 按键
  225. void _press(_Key k) {
  226. switch (k.act) {
  227. case _Act.char:
  228. if (k.mergeDigit) {
  229. // 数字键并入左边那个数字字面量,`42` 才是一个数而不是两个节点
  230. _doc.insertChar(k.payload);
  231. } else {
  232. _doc.insert(LitNode(k.payload, display: k.display));
  233. }
  234. case _Act.fn:
  235. _doc.makeFunction(k.payload);
  236. case _Act.fnPrefixed:
  237. // 像 D 这种,第一个参数留空给用户填,其余预置好
  238. _doc.makeFunction(k.payload, prefill: k.prefill);
  239. case _Act.bigOp:
  240. // ∫ / Σ / lim:上下限单独成槽,才画得到习惯位置
  241. final p = k.prefill;
  242. _doc.makeBigOp(
  243. k.payload,
  244. variable: p.isNotEmpty ? p[0] : 'x',
  245. lower: p.length > 1 ? p[1] : '',
  246. upper: p.length > 2 ? p[2] : '',
  247. );
  248. case _Act.sqrt:
  249. _doc.makeFunction('Sqrt');
  250. case _Act.group:
  251. _doc.makeGroup();
  252. case _Act.power:
  253. _doc.makePower();
  254. case _Act.brace:
  255. _doc.makeBrace();
  256. case _Act.newRow:
  257. _doc.addMatrixRow();
  258. case _Act.frac:
  259. _doc.makeFraction();
  260. case _Act.postfix:
  261. // 阶乘是后缀:把光标左边那个节点收进来当操作数
  262. final operand = _doc.takeLeft();
  263. _doc.insert(PostfixNode(
  264. operand: SeqNode(operand == null ? null : [operand]),
  265. ));
  266. case _Act.comma:
  267. _doc.nextArgument();
  268. case _Act.back:
  269. _doc.backspace();
  270. case _Act.clear:
  271. _doc.clear();
  272. case _Act.commit:
  273. _commit();
  274. return; // 提交不改文档,不用刷新
  275. }
  276. _onDocChanged();
  277. }
  278. Future<void> _showPalette() async {
  279. final picked = await showModalBottomSheet<({String value, bool isFn})>(
  280. context: context,
  281. isScrollControlled: true,
  282. showDragHandle: true,
  283. builder: (_) => const _FunctionPalette(),
  284. );
  285. if (picked == null) return;
  286. if (picked.isFn) {
  287. _doc.makeFunction(picked.value);
  288. } else {
  289. _doc.insert(LitNode(picked.value));
  290. }
  291. _onDocChanged();
  292. }
  293. // ------------------------------------------------------------------ UI
  294. @override
  295. Widget build(BuildContext context) {
  296. final session = context.watch<SymjaSession>();
  297. final bar = _contextBar();
  298. return Scaffold(
  299. appBar: AppBar(
  300. title: const Text('计算器'),
  301. actions: [
  302. // 精确 / 近似 切换。默认精确:`1/3` 就是 `1/3`,这是符号计算的意义所在。
  303. TextButton(
  304. onPressed: () {
  305. session.approximate = !session.approximate;
  306. _onDocChanged(); // 立刻按新模式重算预览
  307. },
  308. child: Text(
  309. session.approximate ? '≈ 近似' : '精确',
  310. style: TextStyle(
  311. fontFamily: 'monospace',
  312. fontSize: 13,
  313. color: Theme.of(context).colorScheme.primary,
  314. ),
  315. ),
  316. ),
  317. IconButton(
  318. tooltip: '画图(x ∈ [-6.3, 6.3])',
  319. icon: const Icon(Icons.show_chart),
  320. onPressed: _plotCurrent,
  321. ),
  322. IconButton(
  323. tooltip: '函数面板',
  324. icon: const Icon(Icons.functions),
  325. onPressed: _showPalette,
  326. ),
  327. ],
  328. ),
  329. body: SafeArea(
  330. child: Column(
  331. children: [
  332. _display(context),
  333. ?bar,
  334. const Divider(height: 1),
  335. Expanded(child: _keypad(context)),
  336. ],
  337. ),
  338. ),
  339. );
  340. }
  341. Widget _display(BuildContext context) {
  342. final scheme = Theme.of(context).colorScheme;
  343. final shown = _committed ?? _preview;
  344. return Container(
  345. width: double.infinity,
  346. constraints: const BoxConstraints(minHeight: 132),
  347. padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
  348. color: scheme.surfaceContainerLow,
  349. child: Column(
  350. crossAxisAlignment: CrossAxisAlignment.end,
  351. children: [
  352. // 固定高度 + 超高时纵向滚动。
  353. // 不固定的话,表达式一变高(分式、Σ 带上下限)编辑区就撑大,
  354. // 下面的键盘整体往下跳,手指刚瞄好的键就换位置了。
  355. SizedBox(
  356. height: 104,
  357. child: SingleChildScrollView(
  358. scrollDirection: Axis.vertical,
  359. reverse: true, // 内容超高时把底部(光标那侧)留在视野里
  360. child: ExprEditor(
  361. doc: _doc,
  362. onChanged: _onDocChanged,
  363. onCaretTapped: () => setState(() => _pastePrompt = true),
  364. ),
  365. ),
  366. ),
  367. const SizedBox(height: 6),
  368. // 常显。它就是真正送进引擎的那串文本(也是"复制表达式"复制走的内容),
  369. // 空槽会写成 Null、隐含括号也会露出来。
  370. Text(
  371. _source,
  372. textAlign: TextAlign.right,
  373. maxLines: 2,
  374. overflow: TextOverflow.ellipsis,
  375. style: TextStyle(
  376. fontFamily: 'monospace',
  377. fontSize: 11,
  378. color: scheme.outline,
  379. ),
  380. ),
  381. const SizedBox(height: 6),
  382. SizedBox(
  383. height: 52,
  384. width: double.infinity,
  385. child: GestureDetector(
  386. key: const ValueKey('calc-result'),
  387. // 点结果 = 复制结果
  388. onTap: shown == null ? null : () => _copy(shown.text, '结果'),
  389. behavior: HitTestBehavior.opaque,
  390. child: FittedBox(
  391. fit: BoxFit.scaleDown,
  392. alignment: Alignment.centerRight,
  393. child: _resultView(context, shown),
  394. ),
  395. ),
  396. ),
  397. ],
  398. ),
  399. );
  400. }
  401. Widget _resultView(BuildContext context, SymjaResult? shown) {
  402. final scheme = Theme.of(context).colorScheme;
  403. if (_error != null) {
  404. return SelectableText(
  405. _error!,
  406. style: TextStyle(
  407. fontFamily: 'monospace',
  408. fontSize: 13,
  409. color: scheme.error,
  410. ),
  411. );
  412. }
  413. if (shown == null) return const SizedBox.shrink();
  414. // 用 Text 而不是 SelectableText:点结果是"复制",选中文字反而挡住点击
  415. final plain = Text(
  416. shown.text,
  417. style: const TextStyle(fontFamily: 'monospace', fontSize: 22),
  418. );
  419. final tex = shown.tex;
  420. final body = tex == null
  421. ? plain
  422. : Math.tex(
  423. tex,
  424. mathStyle: MathStyle.display,
  425. textStyle: TextStyle(fontSize: 26, color: scheme.onSurface),
  426. onErrorFallback: (_) => plain,
  427. );
  428. return Row(
  429. mainAxisSize: MainAxisSize.min,
  430. children: [
  431. if (_committed != null) ...[
  432. Icon(Icons.check_circle, size: 16, color: scheme.primary),
  433. const SizedBox(width: 6),
  434. Text('${_committed!.elapsedMs} ms',
  435. style: TextStyle(fontSize: 11, color: scheme.outline)),
  436. const SizedBox(width: 10),
  437. ],
  438. body,
  439. ],
  440. );
  441. }
  442. Widget _keypad(BuildContext context) {
  443. return LayoutBuilder(
  444. builder: (context, box) {
  445. final rows = <List<_Key>>[
  446. // 1 大运算符
  447. [
  448. _Key('∫', _Act.bigOp, payload: 'Integrate', prefill: ['x']),
  449. _Key('Σ', _Act.bigOp,
  450. payload: 'Sum', prefill: ['n', '1', 'Infinity']),
  451. _Key('d/dx', _Act.fnPrefixed, payload: 'D', prefill: ['', 'x']),
  452. _Key('lim', _Act.bigOp, payload: 'Limit', prefill: ['x', '0']),
  453. _Key('solve', _Act.fnPrefixed, payload: 'Solve', prefill: ['', 'x']),
  454. ],
  455. // 2 常用函数
  456. [
  457. _Key('sin', _Act.fn, payload: 'Sin'),
  458. _Key('cos', _Act.fn, payload: 'Cos'),
  459. _Key('tan', _Act.fn, payload: 'Tan'),
  460. _Key('ln', _Act.fn, payload: 'Log'),
  461. _Key('√', _Act.sqrt),
  462. ],
  463. // 3 变量
  464. [
  465. _Key('x', _Act.char, payload: 'x'),
  466. _Key('a', _Act.char, payload: 'a'),
  467. _Key('b', _Act.char, payload: 'b'),
  468. _Key('t', _Act.char, payload: 't'),
  469. _Key('n', _Act.char, payload: 'n'),
  470. ],
  471. // 4 数字与括号
  472. [
  473. _Key('7', _Act.char, payload: '7', mergeDigit: true),
  474. _Key('8', _Act.char, payload: '8', mergeDigit: true),
  475. _Key('9', _Act.char, payload: '9', mergeDigit: true),
  476. _Key('(', _Act.group),
  477. _Key('/', _Act.frac),
  478. ],
  479. [
  480. _Key('4', _Act.char, payload: '4', mergeDigit: true),
  481. _Key('5', _Act.char, payload: '5', mergeDigit: true),
  482. _Key('6', _Act.char, payload: '6', mergeDigit: true),
  483. _Key('×', _Act.char, payload: '*'),
  484. _Key('!', _Act.postfix),
  485. ],
  486. [
  487. _Key('1', _Act.char, payload: '1', mergeDigit: true),
  488. _Key('2', _Act.char, payload: '2', mergeDigit: true),
  489. _Key('3', _Act.char, payload: '3', mergeDigit: true),
  490. _Key('+', _Act.char, payload: '+'),
  491. _Key('−', _Act.char, payload: '-'),
  492. ],
  493. // 7 花括号:矩阵用
  494. [
  495. _Key('0', _Act.char, payload: '0', mergeDigit: true),
  496. _Key('.', _Act.char, payload: '.', mergeDigit: true),
  497. _Key('^', _Act.power),
  498. _Key('{', _Act.brace),
  499. _Key('},{', _Act.newRow, tint: true),
  500. ],
  501. [
  502. _Key('⌫', _Act.back, tint: true),
  503. _Key('CLR', _Act.clear, tint: true),
  504. _Key(',', _Act.comma),
  505. _Key('ANS', _Act.char, payload: '%', tint: true, display: 'ANS'),
  506. _Key('=', _Act.commit, primary: true),
  507. ],
  508. ];
  509. // 7 行 + 6 个间隙,再扣掉 Padding 上下各 6 ——
  510. // box.maxHeight 是 padding **之前**的高度,漏掉会溢出。
  511. final h = (box.maxHeight - 12 - 7 * 6) / 8;
  512. return Padding(
  513. padding: const EdgeInsets.all(6),
  514. child: Column(
  515. children: [
  516. for (var r = 0; r < rows.length; r++) ...[
  517. if (r > 0) const SizedBox(height: 6),
  518. SizedBox(
  519. height: h,
  520. child: Row(
  521. children: [
  522. for (var c = 0; c < rows[r].length; c++) ...[
  523. if (c > 0) const SizedBox(width: 6),
  524. Expanded(child: _keyButton(rows[r][c])),
  525. ],
  526. ],
  527. ),
  528. ),
  529. ],
  530. ],
  531. ),
  532. );
  533. },
  534. );
  535. }
  536. Widget _keyButton(_Key k) {
  537. final scheme = Theme.of(context).colorScheme;
  538. final bg = k.primary
  539. ? scheme.primary
  540. : k.tint
  541. ? scheme.surfaceContainerHighest
  542. : scheme.surfaceContainerLow;
  543. final fg = k.primary ? scheme.onPrimary : scheme.onSurface;
  544. return Material(
  545. // 加 key 是为了让测试能精确定位按键 —— 编辑器里渲染出的字面量(比如 'x')
  546. // 和键盘上同名的按键都符合 find.text,会撞车。
  547. key: ValueKey('key-${k.label}'),
  548. color: bg,
  549. borderRadius: BorderRadius.circular(10),
  550. child: InkWell(
  551. borderRadius: BorderRadius.circular(10),
  552. onTap: () => _press(k),
  553. child: Center(
  554. child: Text(
  555. k.label,
  556. style: TextStyle(
  557. color: fg,
  558. fontSize: k.label.length > 2 ? 13 : 17,
  559. fontFamily: k.label.length > 2 ? null : 'monospace',
  560. ),
  561. ),
  562. ),
  563. ),
  564. );
  565. }
  566. }
  567. enum _Act {
  568. char,
  569. fn,
  570. fnPrefixed,
  571. bigOp,
  572. brace,
  573. newRow,
  574. sqrt,
  575. group,
  576. power,
  577. frac,
  578. postfix,
  579. comma,
  580. back,
  581. clear,
  582. commit,
  583. }
  584. @immutable
  585. class _Key {
  586. final String label;
  587. final _Act act;
  588. final String payload;
  589. /// fnPrefixed 用:第一个参数留空给用户填,其余的预置。
  590. final List<String> prefill;
  591. /// 数字键:并入左边那个数字字面量,而不是各建一个节点。
  592. final bool mergeDigit;
  593. /// 编辑框里显示的名字(和真正送出去的 payload 不同时用)。
  594. final String? display;
  595. final bool tint;
  596. final bool primary;
  597. const _Key(
  598. this.label,
  599. this.act, {
  600. this.payload = '',
  601. this.prefill = const [],
  602. this.mergeDigit = false,
  603. this.display,
  604. this.tint = false,
  605. this.primary = false,
  606. });
  607. }
  608. /// 函数面板:检索 Symja 的两百多个函数名,选中后插入一个函数节点。
  609. class _FunctionPalette extends StatefulWidget {
  610. const _FunctionPalette();
  611. @override
  612. State<_FunctionPalette> createState() => _FunctionPaletteState();
  613. }
  614. class _FunctionPaletteState extends State<_FunctionPalette> {
  615. final _search = TextEditingController();
  616. String _q = '';
  617. @override
  618. void dispose() {
  619. _search.dispose();
  620. super.dispose();
  621. }
  622. @override
  623. Widget build(BuildContext context) {
  624. final q = _q.trim().toLowerCase();
  625. final fns = kSymjaFunctions
  626. .where((f) => q.isEmpty || f.toLowerCase().contains(q))
  627. .toList(growable: false);
  628. return DraggableScrollableSheet(
  629. expand: false,
  630. initialChildSize: 0.75,
  631. maxChildSize: 0.95,
  632. builder: (context, scroll) => Column(
  633. children: [
  634. Padding(
  635. padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
  636. child: TextField(
  637. controller: _search,
  638. autofocus: true,
  639. decoration: InputDecoration(
  640. isDense: true,
  641. hintText: '函数名(共 ${kSymjaFunctions.length} 个)',
  642. prefixIcon: const Icon(Icons.search),
  643. border: const OutlineInputBorder(),
  644. ),
  645. onChanged: (v) => setState(() => _q = v),
  646. ),
  647. ),
  648. // 常量做成可点的 —— 它们从键盘上挪走了,得有个地方能按。
  649. Padding(
  650. padding: const EdgeInsets.symmetric(horizontal: 16),
  651. child: Wrap(
  652. spacing: 8,
  653. runSpacing: 4,
  654. crossAxisAlignment: WrapCrossAlignment.center,
  655. children: [
  656. Text('常量', style: Theme.of(context).textTheme.bodySmall),
  657. for (final c in kSymjaConstants)
  658. ActionChip(
  659. label: Text(
  660. c,
  661. style: const TextStyle(
  662. fontFamily: 'monospace', fontSize: 12),
  663. ),
  664. visualDensity: VisualDensity.compact,
  665. materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
  666. onPressed: () =>
  667. Navigator.pop(context, (value: c, isFn: false)),
  668. ),
  669. ],
  670. ),
  671. ),
  672. const Divider(height: 16),
  673. Expanded(
  674. child: fns.isEmpty
  675. ? const Center(child: Text('没有匹配的函数'))
  676. : ListView.builder(
  677. controller: scroll,
  678. itemCount: fns.length,
  679. itemBuilder: (_, i) => ListTile(
  680. dense: true,
  681. title: Text(
  682. fns[i],
  683. style: const TextStyle(fontFamily: 'monospace'),
  684. ),
  685. // 一句中文说明,挂名字后面
  686. subtitle: Text(
  687. kSymjaFunctionHelp[fns[i]] ?? '',
  688. style: const TextStyle(fontSize: 12),
  689. ),
  690. onTap: () => Navigator.pop(
  691. context, (value: fns[i], isFn: true)),
  692. ),
  693. ),
  694. ),
  695. ],
  696. ),
  697. );
  698. }
  699. }