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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With