Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Underscore "_" before variable name mean for Flutter

Tags:

flutter

dart

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.

  1. Does it also apply to Flutter? Noting that there is no public/protected in Flutter.
  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? In this case, wouldn't the main class be unable to assess the Widget?

Function

Widget _buildRow(WordPair pair) {   final bool alreadySaved = _saved.contains(pair);  // Add this line.   ... } 
like image 213
lonelearner Avatar asked Nov 04 '18 15:11

lonelearner


People also ask

What is the use of _ in Flutter?

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.

What does an underscore before a variable name mean?

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.

Why do variables start with _?

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.

What is underscore in Dart?

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”.


1 Answers

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();   } } 
like image 180
boformer Avatar answered Sep 22 '22 08:09

boformer