Placeholder Image

Subtitles section Play video

  • ♪♪

  • Dart's event loop supports most types of asynchronous operations through futures and streams, but those two alone cannot handle every scenario.

  • For advanced control of futures, reach for a completer.

  • To start, import dart-async, create a new completer, and give it a type.

  • The point of a completer is to access its future attribute, which you can programmatically resolve using the complete method.

  • One common use case for completers is any class which must complete asynchronous setup before completing its primary task.

  • To start, define a class which initializes a completer.

  • This one uses a bool to indicate whether the initialization was successful.

  • Next, add a getter to expose the completer's future.

  • Now, run your initialization code.

  • Then, complete your completer and pass a value that matches your type.

  • Any code that uses this class can now await isReady before calling methods that depend on that setup.

  • And if an instance of my class has already completed its initialization, isReady will resolve immediately.

  • Another fun use case for completers is abstracting away streams.

  • Imagine a class with an input stream and an output stream, and a method that needs to put one value into the input stream and then return the next value that is emitted from the output stream.

  • The only problem with streams is you don't know when that will happen.

  • Set up a completer in your method and immediately return its future.

  • Then, in your listener to the output stream, complete the completer.

  • This will send that new value through the future returned by the increment method.

  • Check the DartPad link in the video description for example code, or for more info on completers and all other Flutter development techniques, head to flutter.dev.

  • ♪♪♪

♪♪

Subtitles and vocabulary

Click the word to look it up Click the word to find further inforamtion about it