Stacky
Stacky

Reputation: 905

Dart/Flutter - access private members of mixin or in derived class

I want to outsource redundant class members into a separate class/mixin. For each class, which uses that class/mixin, I want to decide individually whether the members are gettable and/or settable from the outside.

I'd like to have something like the example below, but that doesn't compile, seemingly because private attributes are not visible when derived or added to a class via with.

So far, I haven't come to a reasonable solution yet. Any ideas?

mixin Person {
  String _firstName;
  String _lastName;
}

class Butcher with Person {
  Butcher({
    String firstName,
    String lastName,
  }) :
        _firstName = firstName,
        _lastName = lastName;

  final String tool = 'knife';
  
  String get firstName => _firstName;
  String get lastName => _lastName;
}

class SecretAgent with Person {
  SecretAgent({
    String firstName,
    String lastName,
  }) :
        _firstName = firstName,
        _lastName = lastName;

  final String tool = 'poison';
          
  String get firstName => _firstName;
  String get lastName => _lastName;
  
  set firstName(String value) => _firstName = value;
  set lastName(String value) => _lastName = value;
  
}

Upvotes: 1

Views: 1791

Answers (1)

jamesdlin
jamesdlin

Reputation: 90015

This has nothing to do with private members. Dart initializer lists can initialize only members of that class, not from any base classes (including mixins). (Member initialization from initializer list executes before base class constructors.)

It should work if you instead move initialization to the constructor body:

class Butcher with Person {
  Butcher({
    String firstName,
    String lastName,
  }) {
    _firstName = firstName;
    _lastName = lastName;
  }

  ...


class SecretAgent with Person {
  SecretAgent({
    String firstName,
    String lastName,
  }) {
    _firstName = firstName;
    _lastName = lastName;
  }

  ...

Upvotes: 1

Related Questions