Search
[Flutter/dart] Private and final class variable
- M.R

- Nov 30, 2022
- 1 min read
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...






Comments