title: Wait for callback to complete in Dart / Flutter
body: <p>Currently writing a flutter app using the <a href="https://github.com/dlutton/flutter_tts" rel="nofollow noreferrer">flutter_tts</a> library.</p>
  
  <p>I have a list of sentences to read out, but currently having trouble waiting for the <strong>setCompletionHandler()</strong> to complete.</p>
  
  <p>How can I wait for the <strong>setCompletionHandler()</strong> callback to complete before moving on to the next string? Currently, the <strong>TTS.speak()</strong> function finishes immediately with the while loop incrementing right away so it only reads out the last sentence in the list.</p>
  
  <pre class="lang-dart prettyprint-override"><code>// code shortened for brevity
  
  FlutterTts TTS;
  TtsState ttsState = TtsState.stopped;
  
  get isPlaying =&gt; ttsState == TtsState.playing;
  get isStopped =&gt; ttsState == TtsState.stopped;
  
  List&lt;String&gt; 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 &lt; sentences.length) {
          readCompleted = await runSpeak(sentences[i].toString());
  
          if (readCompleted)
            i++;
      }
  }
  
  Future&lt;bool&gt; runSpeak(String currentSentence) async {
      TTS.setStartHandler(() {
        setState(() {
          ttsState = TtsState.playing;
        });
      });
  
      TTS.setCompletionHandler(() {
        setState(() {
          ttsState = TtsState.stopped;
        });
      });
  
      await TTS.speak(currentSentence);
  
      return true;
  }
  
  readOutSentences(sentences);
  
  </code></pre>