學習 Flutter 來寫 App,一開始可以先了解 Dart 語法如何使用,像是我會認為 Const 和 Final 是差不多的 Keyword,但實際上呢?
我們直接看以下的例子,就判斷是怎樣的差異,未來寫程式可以更精確地使用-不會被改變的值、物件、類別。🙃

Const
Value must be known at compile-time, const birthday = "2008/12/25"
Can’t be changed after initialized.
Final
Value must be known at run-time, final birthday = getBirthDateFromDB()
Can’t be changed after initialized.
以上,兩者都是為了宣告一個不可變動的 property。最大的區別為『時機點』。
- Final 宣告的 property 是在專案執行(run time)階段的常數。
- Constant 宣告的 property 是在專案編譯(compile time)階段的常數。
final date1 = DateTime.now();
const date2 = DateTime.now(); // Compile error
.
如此簡單,懂了~
參考:
隨意留個言吧:)~