[英]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 中, _
被用作私有变量的命名约定。
_
really be private (inaccessible by other classes) or is it just a naming convention? _
真的是私有的(其他类无法访问)还是只是一个命名约定?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);
...
}
_
make the Widget private too? _
是否也将 Widget 设为私有? In this case, wouldn't the main class be unable to assess the Widget?在这种情况下,主类不是无法评估 Widget 吗?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.