簡體   English   中英

const 構造函數和 no_const 構造函數有什么區別?

[英]What's the difference between const constructor and no_const constructor?

我是 flutter 的新手,並且對它的構造函數感到困惑。

例如:

  • 樣品 1:
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,
    );
  }
}
  • 樣本 2:
class MyContainer extends StatelessWidget {
  final Color color;
  MyContainer({this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
    );
  }
}

我刪除了示例 2 中的constkey ,並且 sample1 和 sample2 都運行良好。

樣本 2 是否存在潛在風險?

當您不希望重建此小部件時,您將使用 const 構造函數。 常量小部件就像常量 pi,它不會改變。 如果您有 state 但是您想使用示例 2 中的普通構造函數,因為小部件會發生變化並且不能保持不變。

因此,當您在有意義的地方使用 const 時(因為它不會被重建),您會獲得輕微的性能提升。

關鍵屬性是另一個主題。

常量

  • 帶有const關鍵字的變量在compile-time初始化,並且在runtime已經賦值。
  • 您不能在class中定義const 但是您可以在function中。
  • 對於 Flutter 特定的,當 state 更新時,構建方法中的所有內容都不會再次初始化。
  • 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM