Flutter/Dart: get and set with private variables
Solution 1
If you want public getter/setter what's the point of having private variable for that?
Just make it a public variable and be done.
If you insist having a private variable with public access, then you still need to add the getter and setter.
Solution 2
Private variable is import due to some reasons, If you conditionally set or get your Class property values then setter and getter is important on private variables. Example given below:
class User {
int _id;
String _firstName;
String _password;
int get id => _id;
set id(int value) {
_id = value;
}
String get firstName => _firstName;
set firstName(String value) {
if(value.length > 7)
_firstName = value;
}
String get password => _password;
set password(String value) {
if(some condition against this value like password)
_password = value;
}
}
Note: you can set condition in getter like setter that I have given in above example.
Comments
-
Little Monkey over 1 year
if I read that setters and getters have to be explicity developed in Dart only when you want to do something more than only retrieve those values. But if I have private variables, like:
Class User { User _user; String _password; }
How can I access to those private variables? Even if I implement the set password like
set password(String value) => _password = value;
It will of course give me an "error".
-
Afinas EM over 4 yearsYou should have to use the getter as well. In the android studio, you can simply generate these on right-clicking the code and taking the generate method (alt + insert).
-
-
Günter Zöchbauer over 5 yearsNo worries. Once you know it many things might look stupid in hindsight :D
-
Rémi Rousselet over 5 yearsIt has some uses! RenderBoxes use it a lot for things like
markNeedsLayout
/markNeedsPaint
-
Günter Zöchbauer over 5 years@RémiRousselet not sure what you mean.
markNeedsLayout
andmarkNeedsPaint
are methods github.com/flutter/flutter/blob/…, github.com/flutter/flutter/blob/… -
Rémi Rousselet over 5 yearsRenderobjects has private variable with public getter/setter where the setter call these markNeedsLayout/Paint
-
Rémi Rousselet over 5 yearsExample: github.com/flutter/flutter/blob/…
-
Günter Zöchbauer over 5 yearsI don't see how this is related to the question. Of course if you want to do additional work when a property is changed, you need a setter. That's the main purpose they exist. But there is no need to use a getter/setter if all they do is returning or updating the private property. Instead just make the property public.
-
PhillipJacobs about 2 yearsLOL wait. How is it useless ? In getters and setters you can perform operations on the value before setting it. Same with getter. No ?