138

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.
  ...
}
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
lonelearner
  • 1,637
  • 4
  • 14
  • 22

3 Answers3

185

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();
  }
}
I'm a frog dragon
  • 7,865
  • 7
  • 46
  • 49
boformer
  • 28,207
  • 10
  • 81
  • 66
98

From the Dart guide

Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore (_), it’s private to its library. For details, see Libraries and visibility.

TheMri
  • 1,217
  • 8
  • 12
2

Private fields also have the advantage that Lint can identify which fields were declared/instantiated and not used, which helps identify human errors.

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.

Kernel James
  • 3,752
  • 25
  • 32