[Flutter/dart] Private and final class variable
Overview
Suppose adding a class variable in dart like below.
Private (don't want to be accessed from outside)
Determine the value by referring to the arguments of the constructor
Once the value is set above, it will not change after that
In such a case, this variable should be final.
I will introduce this method.
Method
The first thing that comes to mind is, why not just set the value inside the constructor.
A final variable cannot be set inside the constructor.
class AClass{
final String _title;
・・・
Genre({required String name}){
_title = setTitle(name); //compile error
}
}
Set value in an initializer.
class AClass{
final String _title;
・・・
Genre({required String name}):
_title = setTitle(name);
}
Lastly
It's easy once you know how, but it took me a while to figure it out, because
I haven't used final much so far...
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Comments