Dart 中的final 和 const

  • 2021 年 10 月 8 日
  • 筆記

Dart 常量和常量值

finalconst 兩個關鍵字用來定義常量,有什麼區別呢?

  1. final 聲明的是運行時常量,const聲明的是編譯時常量

  2. const 可以聲明常量值

舉個例子:

import 'dart:math';
void main() {
  var random = Random();
  final randomNumber = random.nextInt(10);
}

如上所示 random.nextInt(10)就是一個運行時常量,因為隨機數只有在程序運行的時候才會產生。

那麼編譯時常量呢,下面就是編譯時常量,可以說區別很明顯了。

void main() {
    const double PI = 3.14;
    const MAX_AGE = 255;
    const END_MESSAGE = "GAME OVER";
}

什麼是常量值?

List students = const <String>["李白"];

const <String>["李白"]就是一個常量值,但是students是一個變量,所以students是可變的,舉個鮮明的例子。

  List students = const <String>["李華"];
  students[0] = "李華111"; 
  // Error: Uncaught Error: Unsupported operation: indexed set
  List students = const <String>["李華"];
  students =const <String> ['杜甫','李白'];
   print(students); // [杜甫, 李白]

所以這就是dart中的常量和常量值了