How do I make Dart wait for an asynchronous call before switching animations?

By default The text to speech engine uses an async call, this causes the main Dart thread to go on with whatever line of code comes next, this leads up to another setstate() call after the TTS speak function which reverts the animation state from Speaking to Idle almost instantly.

is there any way to avoid this issue?

I want it to work as follows:

setstate(() => _animation = 'Speaking')

wait until the TTS is finished speaking

setstate(() => _animation = 'Idle')

If I'm misunderstanding something, could you please point it out? in case this is how Dart works then if you have any workarounds that'd be great.

Simplified code for inspection:

void _speak(String sentence) async {
    if (!_isSpeaking) {
      setState(() => _animation = 'Speak');
      setState(() => _isSpeaking = true);

      var result = await tts.speak(sentence);
      if (result != null) {
        setState(() => _isListening = false);
        setState(() => _isSpeaking = false);
      }

}

 } else {
      setState(() => _isSpeaking = false);
    }
  }


Read more here: https://stackoverflow.com/questions/67013185/how-do-i-make-dart-wait-for-an-asynchronous-call-before-switching-animations

Content Attribution

This content was originally published by abood bah at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: