Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Dart, how to access a parent private var from a subclass in another file?

I have two classes in Dart, MyClass1 and MyClass2 where MyClass2 extends MyClass1. In some of MyClass2 functions, I want to access a variable that has "private" access privileges in MyClass1. If MyClass1 and MyClass2 are declared in the same dart file, like this:

class MyClass1 {
  double _myprivatevar;
}

class MyClass2 extends MyClass1 {

  MyClass2(double myvar){
    this._myprivatevar = myvar;
  }
}  

everything is fine But now, if MyClass2 is declared in its own dart file:

import 'package:test/myclass1.dart';

class MyClass2 extends MyClass1 {

  MyClass2 (double myvar){
    this._myprivatevar = myvar;
  }
}

I have an error saying:

The setter '_myprivatevar' isn't defined for the class 'MyClass2'. Try importing the library that defines '_myprivatevar', correcting the name to the name of an existing setter, or defining a setter or field named '_myprivatevar'.dart(undefined_setter)

how can I solve this issue and have access to a parent private variable from a subclass defined in another dart file?

like image 584
Thomas Bernard Avatar asked Nov 05 '19 16:11

Thomas Bernard


People also ask

How do you access private variables in subclass?

To access private variables of parent class in subclass you can use protected or add getters and setters to private variables in parent class.. Save this answer. Show activity on this post. You can't access directly any private variables of a class from outside directly.

How do you access the private variable outside the class in flutter?

In order to access a private variable, set Field-object. setAccessible(true) . And this should be mentioned in the class where we are using a private variable. Then obtain the variable by using field object.

How do you access private members of a class in Dart?

In Dart, privacy is at the library level, not the class level. You can access a class's private members from code outside of that class as long as that code is in the same library where the class is defined. (In Java terms, Dart has package private.


1 Answers

You can use @protected annotation for this.

class MyClass1 {
  double _myprivatevar;

  @protected double get myprivatevar => _myprivatevar;

  @protected set myprivatevar(newValue) {
    _myprivatevar = newValue;
  }
    
}

class MyClass2 extends MyClass1 {

  MyClass2(double myvar){
    myprivatevar = myvar;
  }
}  

Source and Github issue link

like image 59
Foumani Avatar answered Sep 27 '22 20:09

Foumani