diff --git a/example/lib/main.dart b/example/lib/main.dart index ac7e671..ae5ec2b 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -41,6 +41,9 @@ class _SpeechRecognitionPageState extends State { String _currentText = ''; String _errorMessage = ''; List _recognitionHistory = []; + + /// 本次录音开始前的文本内容(用于实时追加) + String _baseText = ''; // 录音相关 final List _realtimeResults = []; // 存储实时识别片段 @@ -155,6 +158,7 @@ class _SpeechRecognitionPageState extends State { _recognitionHistory.clear(); _realtimeResults.clear(); _currentText = ''; + _baseText = ''; // 也清空基础文本 _textController.clear(); _errorMessage = ''; }); @@ -472,19 +476,27 @@ class _SpeechRecognitionPageState extends State { setState(() { if (result.recognizedWords.isNotEmpty) { if (result.finalResult) { - // 最终结果:追加到文本框 - print('📱 [Example] 最终识别结果,追加到文本框: ${result.recognizedWords}'); - String currentTextInBox = _textController.text; - if (currentTextInBox.isNotEmpty && - !currentTextInBox.endsWith(' ')) { - currentTextInBox += ' '; // 添加空格分隔 - } - _textController.text = currentTextInBox + result.recognizedWords; - // 最终结果不需要更新_currentText,因为录音已结束 + // 最终结果:确认当前文本,更新base text为下次录音做准备 + print('📱 [Example] 最终识别结果,确认文本: ${result.recognizedWords}'); + _baseText = _textController.text; // 保存当前文本作为下次的基础 + _currentText = ''; // 清空当前识别文本 } else { - // 实时结果:仅用于显示,不追加到文本框 - print('📱 [Example] 实时识别: ${result.recognizedWords}'); + // 实时结果:实时更新到输入框 + print('📱 [Example] 实时识别,更新输入框: ${result.recognizedWords}'); _currentText = result.recognizedWords; + + // 实时更新输入框内容 = 基础文本 + 当前识别文本 + String newText = _baseText; + if (newText.isNotEmpty && !newText.endsWith(' ') && _currentText.isNotEmpty) { + newText += ' '; // 添加空格分隔 + } + newText += _currentText; + + _textController.text = newText; + // 将光标移到最后 + _textController.selection = TextSelection.fromPosition( + TextPosition(offset: newText.length), + ); } } }); @@ -509,13 +521,13 @@ class _SpeechRecognitionPageState extends State { if (_recognitionHistory.length > 10) { _recognitionHistory.removeLast(); } - // 清空当前文本,因为录音已结束 - _currentText = ''; }); } + // 注意:不在这里清空_currentText,因为最终结果会处理 } else { - // 开始录音时清空实时结果缓存 + // 开始录音时记录当前文本作为基础,清空当前识别文本 setState(() { + _baseText = _textController.text; // 记录录音开始前的文本 _realtimeResults.clear(); _currentText = ''; // 清空当前识别文本 });