简体   繁体   English

是否有关于如何在 Flutter 中定义小部件属性可见性的最佳实践?

[英]Is there any best practice of how to define the widget's properties visibility in Flutter?

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):在 Java 中,根据 Effective Java 的建议(第二版第 15 条[“最小化可变性”] 和第一版第 13 条[“支持不变性”]):

Fields are final and private.字段是最终的和私有的。

If a field does not intend to be used externally, it's likely to set it to private , eg,如果一个字段不打算在外部使用,它可能会将其设置为private ,例如,

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 :但是在 Flutter 框架中,几乎所有 Flutter 小部件都使用属性作为公共属性,就像我在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:但是根据我从 Java 中学到的经验,我应该更合理地将属性更改为private ,例如:

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?所以我很好奇,有没有关于 Flutter 小部件的属性可见性的最佳实践(有效)指南?

From Dart Documentation来自Dart 文档

Dart doesn't have the keywords public, protected, and private. Dart 没有关键字 public、protected 和 private。 If an identifier starts with an underscore _, it's private to its Class , so it is different than Java如果标识符以下划线 _ 开头,则它是其Class私有的,因此它不同于Java

So as per you code only:因此,仅根据您的代码:

// these are private entities inside your Class/Activity
final Widget _title;
final bool _centerTitle;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM