In Java, according to the recommendations of Effective Java (Item 15 ["Minimize Mutability"] in the Second Edition and Item 13 ["Favor Immutability"] in the First Edition):
Fields are final and private.
If a field does not intend to be used externally, it's likely to set it to private
, eg,
class CustomAppBar extends View {
public CustomAppBar(Context context, String title, Boolean centerTitle) {
super(context);
this.title = title;
this.centerTitle = centerTitle;
}
private final String title;
private final Boolean centerTitle;
}
But in Flutter framework, almost all Flutter widgets use properties as public property, like what I see in AppBar
:
class AppBar extends StatefulWidget implements PreferredSizeWidget {
AppBar({
this.title,
this.centerTitle,
...
}): ...
final Widget title;
final bool centerTitle;
...
}
But based on the experience I learned from Java, I should make it more reasonable to change the properties to private
, such like:
class CustomAppBar extends StatefulWidget implements PreferredSizeWidget {
CustomAppBar({
Widget title,
bool centerTitle,
}): _title = title,
_centerTitle = centerTitle;
final Widget _title;
final bool _centerTitle;
...
}
So I am curious, is there any best practice(effective) guide of the visibility of the properties of Flutter widgets?
From Dart Documentation
Dart doesn't have the keywords public, protected, and private. If an identifier starts with an underscore _, it's private to its
Class
, so it is different thanJava
So as per you code only:
// these are private entities inside your Class/Activity
final Widget _title;
final bool _centerTitle;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.