Mustufa Ansari
Mustufa Ansari

Reputation: 648

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?

Upvotes: 33

Views: 66618

Answers (4)

Dinesh Falwadiya
Dinesh Falwadiya

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

Tariiq Dusmohamud
Tariiq Dusmohamud

Reputation: 53

In Android studio:

  1. Right click on the variable name on the line where you declare it.
  2. Click on "Show Context Actions" or Option + Enter on Mac
  3. Then click on "Encapsulate Field".

Upvotes: 0

Nagaraj Alagusundaram
Nagaraj Alagusundaram

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.

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.

Upvotes: 28

Günter Zöchbauer
Günter Zöchbauer

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

Related Questions