Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getter/Setter in Flutter using Android Studio

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?

like image 958
Mustufa Ansari Avatar asked Feb 24 '19 16:02

Mustufa Ansari


People also ask

Why use getters and setters flutter?

They're used to set the value of a variable and nothing else. These are often useful when you want to execute some code in response to a variable being assigned a value, or when a properties value needs to be computed when set.

What is the use of getter and setter in Dart?

Getter and setter methods are the class methods used to manipulate the data of the class fields. Getter is used to read or get the data of the class field whereas setter is used to set the data of the class field to some variable.


2 Answers

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
}
like image 172
Günter Zöchbauer Avatar answered Oct 21 '22 13:10

Günter Zöchbauer


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.

enter image description here

enter image description here

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.

like image 22
Nagaraj Alagusundaram Avatar answered Oct 21 '22 15:10

Nagaraj Alagusundaram