[英]What's the difference between const constructor and no_const constructor?
我是 flutter 的新手,並且對它的構造函數感到困惑。
例如:
class MyContainer extends StatelessWidget {
final Color color;
const MyContainer({Key key, this.color}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
color: color,
);
}
}
class MyContainer extends StatelessWidget {
final Color color;
MyContainer({this.color});
@override
Widget build(BuildContext context) {
return Container(
color: color,
);
}
}
我刪除了示例 2 中的const
和key
,並且 sample1 和 sample2 都運行良好。
樣本 2 是否存在潛在風險?
當您不希望重建此小部件時,您將使用 const 構造函數。 常量小部件就像常量 pi,它不會改變。 如果您有 state 但是您想使用示例 2 中的普通構造函數,因為小部件會發生變化並且不能保持不變。
因此,當您在有意義的地方使用 const 時(因為它不會被重建),您會獲得輕微的性能提升。
關鍵屬性是另一個主題。
常量
const
關鍵字的變量在compile-time
初始化,並且在runtime
已經賦值。class
中定義const
。 但是您可以在function
中。const
在運行時不能更改。什么時候使用常量?
-
Use const: If you are sure that a value isn't going to be changed when running your code. For example, when you declare a sentence that always remains the same.
當您將 const 與構造函數一起使用時,它是編譯時常量,並且構造函數中給出的所有值都必須是常量,
嘗試為 const 構造函數提供非恆定值以查看差異
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.