Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.
  ...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...