From ea32370fccff9b160f1a94eed94f9ec101508725 Mon Sep 17 00:00:00 2001 From: Max Date: Tue, 9 Sep 2025 11:08:44 +0800 Subject: [PATCH] Improve text input behavior: append recognition results to text field - Change from replacing current text to appending final results - Distinguish between real-time results (display only) and final results (append to text) - Add proper spacing between appended text segments - Maintain history of individual recognition segments - Clear current text when starting new recording session --- example/lib/main.dart | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 3b3f3d6..c1315c2 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -15,7 +15,7 @@ class MyApp extends StatelessWidget { title: 'YX ASR Example', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), - useMaterial3: true, + useMaterial3: false, // 暂时禁用Material 3以避免着色器编译问题 ), home: const SpeechRecognitionPage(), ); @@ -95,8 +95,6 @@ class _SpeechRecognitionPageState extends State { if (result.recognizedWords.isNotEmpty) { print('📱 [Example] 实时识别: ${result.recognizedWords}'); _currentText = result.recognizedWords; - // 更新文本框显示 - _updateTextController(); } }); }); @@ -534,12 +532,22 @@ class _SpeechRecognitionPageState extends State { print( '📱 [Example] RecordingButton 接收到识别结果: "${result.recognizedWords}"'); setState(() { - // 更新当前识别的文本(实时显示) if (result.recognizedWords.isNotEmpty) { - print('📱 [Example] 实时识别: ${result.recognizedWords}'); - _currentText = result.recognizedWords; - // 更新文本框显示 - _updateTextController(); + if (result.finalResult) { + // 最终结果:追加到文本框 + print('📱 [Example] 最终识别结果,追加到文本框: ${result.recognizedWords}'); + String currentTextInBox = _textController.text; + if (currentTextInBox.isNotEmpty && + !currentTextInBox.endsWith(' ')) { + currentTextInBox += ' '; // 添加空格分隔 + } + _textController.text = currentTextInBox + result.recognizedWords; + _currentText = result.recognizedWords; // 保存当前识别结果 + } else { + // 实时结果:仅用于显示,不追加到文本框 + print('📱 [Example] 实时识别: ${result.recognizedWords}'); + _currentText = result.recognizedWords; + } } }); }, @@ -555,7 +563,7 @@ class _SpeechRecognitionPageState extends State { }); if (!isListening) { - // 录音结束后,将当前识别的文本保存到历史记录 + // 录音结束后,将当前识别结果保存到历史记录(如果有的话) if (_currentText.isNotEmpty) { setState(() { _recognitionHistory.insert(0, _currentText); @@ -566,9 +574,10 @@ class _SpeechRecognitionPageState extends State { }); } } else { - // 开始录音时清空之前的结果 + // 开始录音时清空实时结果缓存 setState(() { _realtimeResults.clear(); + _currentText = ''; // 清空当前识别文本 }); } },