with reference to the Flutter tutorial, I encountered an underscore, _
.
I know that in Java, _
is used as a naming convention for a private variable.
_
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? In this case, wouldn't the main class be unable to assess the Widget?Widget _buildRow(WordPair pair) { final bool alreadySaved = _saved.contains(pair); // Add this line. ... }
The builder pattern is an essential building block for creating composable UIs in Flutter. As such, Flutter exposes convenience builder types that are used as arguments in many widget classes.
An underscore in front usually indicates an instance variable as opposed to a local variable. It's merely a coding style that can be omitted in favor of "speaking" variable names and small classes that don't do too many things. Follow this answer to receive notifications.
The underscore in variable names is completely optional. Many programmers use it to differentiate private variables - so instance variables will typically have an underscore prepended to the name. This prevents confusion with local variables.
Dart uses a leading underscore in an identifier to mark members and top-level declarations as private. This trains users to associate a leading underscore with one of those kinds of declarations. They see “_” and think “private”.
It's not just a naming convention. Underscore fields, classes and methods will only be available in the .dart
file where they are defined.
It is common practice to make the State
implementation of a widget private, so that it can only be instantiated by the corresponding StatefulWidget
:
class MyPage extends StatefulWidget { @override _MyPageState createState() => _MyPageState(); } class _MyPageState extends State<MyPage> { @override Widget build(BuildContext context) { return Container(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With