Reputation: 648
I am making an app in Flutter and i am using Android studio for that. But it is not making getter and setter by using alt+insert command to generate getter and setter automatically.is there any way of doing this?
Upvotes: 33
Views: 66618
Reputation: 809
Android Studio Dart
I was also stuck on the same, I found out that we have to declare our private variable names with an underscore ( _TestVariable ).
Then use the shortcut Alt + insert (On Windows) to generate automatic Getters/Setters
class Books
{
late int _id;
int get id => _id;
set id(int value) {
_id = value;
}
}
Upvotes: 2
Reputation: 53
In Android studio:
Upvotes: 0
Reputation: 2459
I didn't clearly understand your questions but check if this helps.
String _myValue = "Hello World";
Now press Comman+N in mac and select Getter and Setter.
Now that you can see the Getter and Setter generated for you.
String _myValue = "Hello World";
String get myValue => _myValue;
set myValue(String value) {
_myValue = value;
}
Ensure that you use "_" as a prefix for the private variables.
To understand getter and setter in dart follow this youtube video.
EDIT:
Noticing the higher votes for my answer, I'm responsible to clarify a few things here. As rightly mentioned by Günter Zöchbauer, explicit getter/setter declarations are not necessary for Dart.
Upvotes: 28
Reputation: 657416
You don't need that in Dart.
A field is equivalent to a getter/setter pair. A final field is equivalent to a getter.
You change it only to actual getters/setters if additionally logic is required and this change is non-breaking for users of that class.
Public getter/setter methods for private fields is an anti-pattern in Dart if the getters/setters don't contain additional logic.
class Foo {
String bar; // normal field (getter/setter)
final String baz; // read-only (getter)
int _weight;
set weight(int value) {
assert(weight >= 0);
_weight = value;
}
int get weight => _weight
}
Upvotes: 53