Reputation: 31
Sink<List<FoodItem>> get listSink => _listController.sink;
Can someone explain to me what does the (get) do ?
this is the default sink function
Upvotes: 2
Views: 1873
Reputation: 1909
To add to @Maxouille's answer:
If you make a property public in Java, and then decide to make it private (because you had to add some additional logic in your get/set methods), calling syntax would change - e.g. instead of A.nValue++;
you would have A.setNValue(A.getNValue()++);
.
This is why convention in Java is to make all properties private from the beginning, and wrap them with get/set methods. This ends up with bunch of code that does nothing, but is there 'just in case'.
What this nice syntax enables you is to convert your public properties easily to private properties with get/set wrapper methods - without changing calling code.
In the above example - property nValue
could have started as a simple int property. Once you decide to make it private - you change your class like in the example above: create a new private variable _n
and convert your nValue into get/set properties:
int get nValue => _n;
set nValue(int newValue) => _n=newValue;
Your calling code would still remain the same nValue++;
Upvotes: 1
Reputation: 2911
This is the syntax of getter methods in dart.
You have a private parameter defined by the _
. Every variable that starts with an underscore is considered as private and can't be read outside of the class. From the documentation :
Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore _, it’s private to its library.
The getter syntax is something like :
Return type
get myVarName => the private value you want to return
Imagine this very simple class:
class A {
int _n = 42;
int get nValue => _n;
}
In order to access the value of n
from class A, I need to use a getter as n
is private.
A myClass = A();
A.n; // Error as n is private
A.nValue; // Return 42.
Upvotes: 4
Reputation: 729
The keyword get
indicates a getter in dart.
To be more specific, a getter is part of the class interface that allows you to retrieve a certain value from a class instance. In Dart, you can think of it almost like a method that doesn't take parameters and uses syntax that is similar to accessing a field value (i.e., attribute) from a class instance.
For example,
void main() {
Item myItem = Item(initialCost: 1000);
print(myItem.cost); // 2002
myItem.cost = 100; // Error because there is no setter 'cost'
}
class Item{
int _privateCost;
int initialCost;
int get cost {
return _privateCost * 2;
};
// constructor
Item({this.initialCost}){
_privateCost = initialCost + 1;
}
}
Upvotes: 0