簡體   English   中英

Dart:如何聲明符合 typedef 而沒有警告的頂級 function?

[英]Dart: How to declarare a top level function that complies with a typedef without warnings?

我知道這個問題 它不是重復的,因為它沒有提到typedefs

我有這個typedef

typedef Prefetcher = Future<void> Function(
    MarkdocNode node, PrefetchContext context);

現在我正在嘗試定義符合Prefetcher簽名的頂級函數。

但是當我這樣做時:

final Prefetcher prefetchTranslatedSentences = (node, context) async {};

我收到這個警告:

信息:使用 function 聲明將 function 綁定到名稱。 (prefer_function_declarations_over_variables 在 [anglio_mobile] lib/components/markdown/prefetchers/translated_sentence_prefetcher.dart:3)

我了解 Dart 希望我不要將 function 分配給變量,而是直接創建 function

prefetchTranslatedSentences(node, context) async {}

但是上面的問題是不能保證prefetchTranslatedSentences會遵守typedef

如何在不收到此警告的情況下創建符合typedefs的頂級函數?

我認為您不能直接定義 function 並保證它符合typedef 但是,如果您的 function 實現不匹配,您可能會很快從其他地方的編譯錯誤中發現。 如果你不這樣做,那么你可以調整你的代碼以確保它確實會產生這樣的錯誤:

  • 添加一個測試,嘗試將您的 function 與typedef一起使用。 如果typedef和您的 function 是某些公共 API 的一部分,那么您可能無論如何都應該對它們進行測試。 最低限度:

     void main() { Prefetcher _ = prefetchTranslatedSentences; }
  • 添加一個間接級別:

     Future<void> _prefetchTranslatedSentences( MarkdocNode node, PrefetchContext context, ) async { //... } final Prefetcher prefetchTranslatedSentences = _prefetchTranslatedSentences;
  • 或者只是使用// ignore: prefer_function_declarations_over_variables lint。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM