I have a variable named number
and a class which sets a variable to number
in its constructor. I then change the value of number
but the number
in the class doesn't update. Here's my code:
void fn1() {
int number = 5;
SomeClass someClass = SomeClass(number);
// Do some other things which take a long time
number = 2;
someClass.printer(); // prints 5. expect 2
}
class SomeClass {
int nestedNum;
SomeClass(this.nestedNum) {
printer();
}
void printer() {
print(nestedNum);
}
}
How can I get nestedNum
to update anytime number
is changed?
So the hacky/easy solution would be anytime I change number
in fn1
, I need change nestedNum
in someClass
: like this: someClass.nestedNum = 2
. The issue with that is if I have multiple classes I would have to go through each one to change the variable.
Another solution I thought of, was to never pass number
into someClass
, but instead pass this
and access number
using this
. The issue with that is again, if I have multiple classes each needing to access a different variable from fn1
.
The only way for nestedNum
to change when number
changes is to let nestedNum
read from number
. Dart does not allow references or pointers to variables to be passed around. What you can do is to pass a function to SomeClass
which provides the value each time it's needed.
void fn1() {
int number = 5;
SomeClass someClass = SomeClass(() => number);
// Do some other things which take a long time
number = 2;
someClass.printer(); // prints 2!
}
class SomeClass {
final int Function() _nestedNum;
int get nestedNum => _nestedNum();
SomeClass(int Function() nestedNum) : _nestedNum = nestedNum {
printer();
}
void printer() {
print(nestedNum);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments