这两种类型的参数有什么区别?
What's the difference between these two types of parameters?
class Example extends StatefulWidget {
final String string;
Example(this.string);
@override
_ExampleState createState() => _ExampleState();
}
class Example2 extends StatefulWidget {
final String string;
const Example2(Key key, this.string) : super(key: key);
@override
_Example2State createState() => _Example2State();
}
我无法准确理解这两者之间的区别(如果有的话)。
唯一的区别是接受密钥。键用于向 Flutter 提供有关小部件的信息。它们可以帮助 Flutter 记住小部件的滚动位置,或者跟踪状态。
通常,键是可选的,这意味着您不必为所有小部件指定它们。但根据您的用例,您最终可能需要它们。
综上所述,没有明显区别。唯一的区别是一个包含密钥而另一个不包含密钥。
另外,请注意它前面有一个 const。这有助于告诉 Flutter,如果传递给小部件的参数是常量,则不需要重建小部件。
在此处了解有关密钥的更多信息:https://www.youtube.com/watch?v=kn0EOS-ZiIc
class Example extends StatefulWidget {
final String string;
Example(this.string);
@override
_ExampleState createState() => _ExampleState();
}
class Example2 extends StatefulWidget {
final String string;
const Example2(Key key, this.string) : super(key: key);
@override
_Example2State createState() => _Example2State();
}
我无法准确理解这两者之间的区别(如果有的话)。
唯一的区别是接受密钥。键用于向 Flutter 提供有关小部件的信息。它们可以帮助 Flutter 记住小部件的滚动位置,或者跟踪状态。
通常,键是可选的,这意味着您不必为所有小部件指定它们。但根据您的用例,您最终可能需要它们。
综上所述,没有明显区别。唯一的区别是一个包含密钥而另一个不包含密钥。
另外,请注意它前面有一个 const。这有助于告诉 Flutter,如果传递给小部件的参数是常量,则不需要重建小部件。
在此处了解有关密钥的更多信息:https://www.youtube.com/watch?v=kn0EOS-ZiIc