简体   繁体   English

变量名前的下划线“_”对 Flutter 意味着什么

[英]What does Underscore "_" before variable name mean for Flutter

with reference to the Flutter tutorial, I encountered an underscore, _ .参考Flutter教程,我遇到了一个下划线, _

I know that in Java, _ is used as a naming convention for a private variable.我知道在 Java 中, _被用作私有变量的命名约定。

  1. Does it also apply to Flutter?它也适用于 Flutter 吗? Noting that there is no public/protected in Flutter.请注意,Flutter 中没有 public/protected。
  2. Will the _ really be private (inaccessible by other classes) or is it just a naming convention? _真的是私有的(其他类无法访问)还是只是一个命名约定?

Variable多变的

class RandomWordsState extends State<RandomWords> {
  final List<WordPair> _suggestions = <WordPair>[];
  final Set<WordPair> _saved = new Set<WordPair>();
  final TextStyle _biggerFont = const TextStyle(fontSize: 18.0);
  ...
}
  1. Does the _ make the Widget private too? _是否也将 Widget 设为私有? In this case, wouldn't the main class be unable to assess the Widget?在这种情况下,主类不是无法评估 Widget 吗?

Function功能

Widget _buildRow(WordPair pair) {
  final bool alreadySaved = _saved.contains(pair);  // Add this line.
  ...
}

It's not just a naming convention.只是一个命名约定。 Underscore fields, classes and methods will only be available in the .dart file where they are defined.下划线字段、类和方法仅在定义它们的.dart文件中可用。

It is common practice to make the State implementation of a widget private, so that it can only be instantiated by the corresponding StatefulWidget :通常的做法是将小部件的State实现设为私有,以便它只能由相应的StatefulWidget实例化:

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

From the Dart guide飞镖指南

Unlike Java, Dart doesn't have the keywords public, protected, and private.与 Java 不同,Dart 没有关键字 public、protected 和 private。 If an identifier starts with an underscore (_), it's private to its library.如果标识符以下划线 (_) 开头,则它对其库是私有的。 For details, see Libraries and visibility .有关详细信息,请参阅库和可见性

Private fields also have the advantage that Lint can identify which fields were declared/instantiated and not used, which helps identify human errors.私有字段的另一个优点是 Lint 可以识别哪些字段已声明/实例化和未使用,这有助于识别人为错误。

If you declare a public field, the field may be accessed by classes outside the class in the future and so Lint cannot warn you if you added the field by mistake.如果您声明一个公共字段,该字段将来可能会被类外的类访问,因此如果您错误地添加了该字段,Lint 不会警告您。

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

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