Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

dart - dart中常量值的用途是什么?(What is the use of constant values in dart?)

As described in the documentations:

(如文档中所述:)

The const keyword isn't just for declaring constant variables.

(const关键字不仅用于声明常量变量。)

You can also use it to create constant values, as well as to declare constructors that create constant values.

(您也可以使用它来创建常量值,以及声明创建常量值的构造函数。)

Any variable can have a constant value.

(任何变量都可以具有恒定值。)

Can someone explain the use of constant values?

(有人可以解释常量值的使用吗?)

  ask by Bewar Salah translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
void main() {
  simpleUse();
  finalUse();
  constUse();
}

simpleUse() {
  print("
simple declaration");
  var x = [10];
  print('before: $x');
  x = [5];//changing reference allowed
  x.add(10);//changing content allowed
  print('after: $x');
}

finalUse() {
  print("
final declaration");
  final x = [10];
  print('before: $x');

  // x = [10,20]; //nope changing reference is not allowed for final declaration

  x.add(20); //changing content is allowed
  print('after: $x');
}

constUse() {
  print("
const declaration");
  const x = [10];
  print('before: $x');

  // x = [10,20]; //nope -> changing reference is not allowed for final declaration

  // x.add(20);//nope -> changing content is not allowed
  print('after: $x');
}

Also, variables are simple values like x = 10;

(另外,变量是简单值,例如x = 10;)
values are instances of enums, list, maps, classes, etc.

(值是枚举,列表,映射,类等的实例。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...