srbrussell
srbrussell

Reputation: 161

Wait for callback to complete in Dart / Flutter

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);

Upvotes: 1

Views: 3160

Answers (3)

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!

Upvotes: 2

orser
orser

Reputation: 164

To wait for the callback use the await keyword:

await TTS.setCompletionHandler(() {
  setState(() {
    ttsState = TtsState.stopped;
  });
});

Upvotes: 0

Dilip Sharma
Dilip Sharma

Reputation: 71

Set setCompletionHandler like following to speak all sentences of the list one by one.

List<String> sentences = ['Hello, World', 'How are you?', 'The quick brown fox jumps over the lazy dog']

int i = 0;

FlutterTts flutterTts = FlutterTts();

await flutterTts.speak(sentences[i]);

flutterTts.setCompletionHandler(() async {
  if (i < sentences.length - 1) {
    i++;
    await flutterTts.speak(sentences[i]);
  }
});

Upvotes: 0

Related Questions