Home > Enterprise >  Is there @friend functionality to accompany @protected?
Is there @friend functionality to accompany @protected?

Time:07-07

I'm using the Dart annotation @protected because I want to limit a member to only be called from a single other class, like so

class Foo {
  @projected
  void doSomethingSpecial() {}
}

class Bar {
  final foo = Foo();
  consumeDoSomethingSpecial() {
    foo.doSomethingSpecial();
  }
}

Understandably, foo.doSomethingSpecial() triggers the warning

    The member 'doSomethingSpecial' can only be used within instance members of subclasses...

In the C world I would annotate Bar as a friend of Foo to permit this call but I'm not seeing the equivalent annotation in Dart?

I did see that I can suppress a warning by adding

// ignore: the_appropriate_lint_rule

above the line with the warning but I'm not seeing a lint rule that applies to using the @protected annotation?

CodePudding user response:

"friend" in Dart is essentially implemented by ensuring that the identifiers are "library-local" (begin with underscore), and all friends are in the same library. A library in Dart is typically just a single file; however, using part/part-of, it can span multiple files.

Any reference to an underscore-prefixed identifier is in-scope for the same library, but out of scope anywhere else, even if you import that file.

  •  Tags:  
  • dart
  • Related