Reputation: 7809
When I use VSCode snippet Extract Widget
, I have the following :
class MyExtractedWidget extends StatelessWidget {
const MyExtractedWidget({
Key key,
@required T someVariable,
}) : _someVariable = someVariable,
super(key: key);
final T _someVariable;
@override
Widget build(BuildContext context){ return Container(); }
}
However, I am used to write constructors the following way :
class MyExtractedWidget extends StatelessWidget {
const MyExtractedWidget({
Key key,
@required this.someVariable, // Directly accessing variable using "this"
}) : super(key: key);
final T someVariable;
@override
Widget build(BuildContext context){ return Container(); }
}
Do you know why snippets' constructors use a temporary variable instead of directly writing in the variable?
Is it related to encapsulation? If yes, I cannot understand why, as an extracted Widget is written in the same file, and that "underscored" variables are accessible in whole file.
I tried with another widget and I have a kind of mix :
class Test extends StatelessWidget {
const Test({
Key key,
@required List<SortedExpense> sortedExpenses,
@required this.expensesSink,
}) : _sortedExpenses = sortedExpenses, super(key: key);
final List<SortedExpense> _sortedExpenses;
final StreamSink<List<Expense>> expensesSink;
...
Upvotes: 0
Views: 1356
Reputation: 277147
This is based on the privacy of the variables you're extracting.
For example, the following widget:
Text(_count.toString())
will generate:
class MyName extends StatelessWidget {
const MyName({
Key key,
@required int count,
}) : _count = count, super(key: key);
final int _count;
@override
Widget build(BuildContext context) {
return Text(_count.toString());
}
}
while this widget:
Text(count.toString())
will create:
class MyName extends StatelessWidget {
const MyName({
Key key,
@required this.count,
}) : super(key: key);
final int count;
@override
Widget build(BuildContext context) {
return Text(count.toString());
}
}
Upvotes: 1