@@ -216,10 +216,11 @@ class FlutterTtsPlugin : MethodCallHandler, FlutterPlugin {
216216
217217 private val onInitListenerWithCallback: TextToSpeech .OnInitListener =
218218 TextToSpeech .OnInitListener { status ->
219- // Handle pending method calls ( sent while TTS was initializing)
219+ // Safely handle any pending method calls sent while TTS was initializing.
220220 synchronized(this @FlutterTtsPlugin) {
221221 ttsStatus = status
222- for (call in pendingMethodCalls) {
222+ // FIX 1: Iterate over a copy of the list to avoid ConcurrentModificationException.
223+ for (call in pendingMethodCalls.toList()) {
223224 call.run ()
224225 }
225226 pendingMethodCalls.clear()
@@ -238,19 +239,28 @@ class FlutterTtsPlugin : MethodCallHandler, FlutterPlugin {
238239 Log .e(tag, " getDefaultLocale: " + e.message)
239240 }
240241
241- engineResult!! .success(1 )
242+ // FIX 2: Only reply once per request to avoid "Reply already submitted" crash.
243+ if (engineResult != null ) {
244+ engineResult!! .success(1 )
245+ engineResult = null // Mark as handled to prevent double-reply.
246+ }
242247 } else {
243- engineResult!! .error(" TtsError" ," Failed to initialize TextToSpeech with status: $status " , null )
248+ // FIX 2: Only reply once per request to avoid "Reply already submitted" crash.
249+ if (engineResult != null ) {
250+ engineResult!! .error(" TtsError" ," Failed to initialize TextToSpeech with status: $status " , null )
251+ engineResult = null // Mark as handled to prevent double-reply.
252+ }
244253 }
245- // engineResult = null
254+ // No need to set engineResult = null here; already handled above.
246255 }
247256
248257 private val onInitListenerWithoutCallback: TextToSpeech .OnInitListener =
249258 TextToSpeech .OnInitListener { status ->
250- // Handle pending method calls ( sent while TTS was initializing)
259+ // Safely handle any pending method calls sent while TTS was initializing.
251260 synchronized(this @FlutterTtsPlugin) {
252261 ttsStatus = status
253- for (call in pendingMethodCalls) {
262+ // FIX 1: Iterate over a copy of the list to avoid ConcurrentModificationException.
263+ for (call in pendingMethodCalls.toList()) {
254264 call.run ()
255265 }
256266 pendingMethodCalls.clear()
@@ -812,4 +822,4 @@ class FlutterTtsPlugin : MethodCallHandler, FlutterPlugin {
812822 audioManager?.abandonAudioFocus(null )
813823 }
814824 }
815- }
825+ }
0 commit comments