Placeholder Image

字幕列表 影片播放

由 AI 自動生成
  • ♪♪

    ♪♪

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

    Dart 的事件循環通過期貨和流支持大多數類型的異步操作,但僅靠這兩種方式並不能處理所有情況。

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

    如需對期貨進行高級控制,請使用完成器。

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

    首先,導入 dart-async,創建一個新的完成器,並給它一個類型。

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

    補全器的作用是訪問其 future 屬性,您可以使用 complete 方法以編程方式解決這個問題。

  • 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.

    這個選項使用一個 bool 來表示初始化是否成功。

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

    接下來,添加一個 getter 來顯示完成程序的未來。

  • 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.

    任何使用該類的代碼現在都可以在調用依賴於該設置的方法之前等待 isReady。

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

    如果我的類的實例已經完成初始化,isReady 會立即解析。

  • 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.

    這將通過增量方法返回的 future 發送新值。

  • 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.

    查看視頻描述中的 DartPad 鏈接以獲取示例代碼,或訪問 flutter.dev 以獲取更多有關 completers 和所有其他 Flutter 開發技術的資訊。

  • ♪♪♪

    ♪♪♪

♪♪

♪♪

字幕與單字
由 AI 自動生成

單字即點即查 點擊單字可以查詢單字解釋