使用VSCode代码段Extract Widget
时,我有以下内容:
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(); }
}
但是,我习惯于通过以下方式编写构造函数:
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(); }
}
您知道为什么代码片段的构造函数使用临时变量而不是直接写入变量吗?
与封装有关吗?如果是的话,我不明白为什么,因为将提取的Widget写在同一文件中,并且在整个文件中都可以访问“加下划线的”变量。
我尝试了另一个小部件,但有一种混合方式:
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;
...
答案 0 :(得分:1)
这是基于您要提取的变量的私密性。
例如,以下小部件:
Text(_count.toString())
将生成:
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());
}
}
在此小部件中:
Text(count.toString())
将创建:
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());
}
}