Wait for callback to complete in Dart / Flutter

1,919

Forgive about the setCompletionHandler)

You can use such async functions:

  Future<void> _speak(String _text) async {
    if (_text != null && _text.isNotEmpty) {
      await flutterTts.awaitSpeakCompletion(true);
      await flutterTts.speak(_text);
    }
  }

  readAllSentencesList(List<String> allSentences) async {
    for (int i=0; i<allSentences.length; i++){
      await _speak(allSentences[i]);
    }
  }

Don't forget to use last flutter_tts library!

Share:
1,919
srbrussell
Author by

srbrussell

Updated on December 15, 2022

Comments

  • srbrussell
    srbrussell over 1 year

    Currently writing a flutter app using the flutter_tts library.

    I have a list of sentences to read out, but currently having trouble waiting for the setCompletionHandler() to complete.

    How can I wait for the setCompletionHandler() callback to complete before moving on to the next string? Currently, the TTS.speak() function finishes immediately with the while loop incrementing right away so it only reads out the last sentence in the list.

    // code shortened for brevity
    
    FlutterTts TTS;
    TtsState ttsState = TtsState.stopped;
    
    get isPlaying => ttsState == TtsState.playing;
    get isStopped => ttsState == TtsState.stopped;
    
    List<String> sentences = ['Hello, World', 'How are you?', 'The quick brown fox jumps over the lazy dog'];
    
    @override
    void initState() {
        super.initState();
        TTS = FlutterTts();
    }
    
    void readOutSentences(sentences) async {
        int i = 0;
        bool readCompleted = false;
    
        while (i < sentences.length) {
            readCompleted = await runSpeak(sentences[i].toString());
    
            if (readCompleted)
              i++;
        }
    }
    
    Future<bool> runSpeak(String currentSentence) async {
        TTS.setStartHandler(() {
          setState(() {
            ttsState = TtsState.playing;
          });
        });
    
        TTS.setCompletionHandler(() {
          setState(() {
            ttsState = TtsState.stopped;
          });
        });
    
        await TTS.speak(currentSentence);
    
        return true;
    }
    
    readOutSentences(sentences);
    
    
    • Gabriel S
      Gabriel S over 4 years
      Which function do you want to wait for?
    • srbrussell
      srbrussell over 4 years
      TTS.setCompletionHandler() runs after TTS.speak() is completed. Need to wait/listen to the TTS.setCompletionHandler() function before incrementing the while loop.
    • Gabriel S
      Gabriel S over 4 years
      Shouldn't you declare the completion and start handlers outside of runSpeak and just calling them inside that function? I think that because you just declare the completion and start handlers in the function, Dart just calls TTS.speak(currentSentence) because the other two are just declarations.