'Flutter/Dart: getters with a parameter
I can't understand how this works. In the class:
Function(int) get myGet {
return myStream.sink.add;
}
and its implementation in a screen:
myObject.myGet(33);
and adds to the stream the number.
Solution 1:[1]
When you call myGet
you're actually calling myStream.shink.add
.
void add(int a) {
...
}
and
Function(int) add = (int a) {
...
}
are same things.
Functions are a types too. Function names (eg: myStream.shink.add
, myObject.myGet
, print
, ...) are pointer constants (since you can not assign another function to print
on dart) pointing to address of the matching function on memory.
PS: In javascript the predefined functions are like variables not constants since you can change default functions (eg: console.log) with your own handlers.
When you call print
compiler changes print with matching function address and when you call print('Hello')
your arguments sent to that address. In your case the same thing happens too. But not on compile time, instead on runtime.
myGet
is a getter returns type of function pointer. On runtime when you call myGet
it returns address of myStream.shink.add
. Adding parentheses after function calls it. Since you re calling myGet
and it points to myStream.shink.add
you're actually calling myStream.shink.add(33)
.
Basically:
myObject.myGet = myStream.sink.add;
Solution 2:[2]
Why not just make a public function?
void add(int x) => myStream.sink.add(x);
Solution 3:[3]
Alternative option is using extensions so you can use this
as a parameter
extension ContextExtension on BuildContext {
double get sectionHorizontalPadding {
final screenWidth = MediaQuery.of(this).size.width;
return screenWidth > LandingDimensions.bodyMaxWidth
? (screenWidth - LandingDimensions.bodyMaxWidth) / 2
: 0.0;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Patrick Lumenus |
Solution 3 | amorenew |