Home > front end >  Dart: How to declarare a top level function that complies with a typedef without warnings?
Dart: How to declarare a top level function that complies with a typedef without warnings?

Time:09-10

I know about this question. It's not a duplicate because it doesn't mention typedefs

I have this typedef:

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

Now I'm trying to define top level functions that comply with the Prefetcher signature.

but when I do this:

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

I'm getting this warning:

info: Use a function declaration to bind a function to a name. (prefer_function_declarations_over_variables at [anglio_mobile] lib/components/markdown/prefetchers/translated_sentence_prefetcher.dart:3)

I understand that Dart wants me to NOT assign a function to a variable, but rather create a function directly like

prefetchTranslatedSentences(node, context) async {}

but the problem of the above is that there is no guarantee that prefetchTranslatedSentences will comply with the typedef

How do I create top-level functions that comply with typedefs without getting this warning?

CodePudding user response:

I don't think that you can directly define a function with an inherent guarantee that it conforms to a typedef. However, if your function implementation doesn't match, you'd probably find out pretty quickly from a compilation error somewhere else anyway. And if you don't, then you can adjust your code to ensure that it does generate such an error:

  • Add a test that attempts to use your function with the typedef. If the typedef and your function are part of some public API, you probably should have a test for them anyway. At a minimum:

    void main() {
      Prefetcher _ = prefetchTranslatedSentences;
    }
    
  • Add a level of indirection:

    Future<void> _prefetchTranslatedSentences(
      MarkdocNode node,
      PrefetchContext context,
    ) async {
      // ...
    }
    
    final Prefetcher prefetchTranslatedSentences = _prefetchTranslatedSentences;
    
  • Or just ignore the lint with // ignore: prefer_function_declarations_over_variables.

  • Related