Dart 编程 - 变量



变量是“内存中命名的空间”,用于存储值。换句话说,它充当程序中值的容器。变量名称称为标识符。以下是标识符的命名规则:

  • 标识符不能是关键字。

  • 标识符可以包含字母和数字。

  • 标识符不能包含空格和特殊字符,除了下划线 (_) 和美元符号 ($) 之外。

  • 变量名不能以数字开头。

类型语法

在使用变量之前必须先声明它。Dart 使用 var 关键字来实现这一点。声明变量的语法如下所示:

var name = 'Smith';

Dart 中的所有变量都存储对值的引用,而不是包含值本身。名为 name 的变量包含对值为“Smith”的 String 对象的引用。

Type Syntax

Dart 通过在变量名前添加数据类型来支持**类型检查**。类型检查确保变量仅保存特定于数据类型的数据。其语法如下所示:

String name = 'Smith'; 
int num = 10;

请考虑以下示例:

void main() { 
   String name = 1; 
}

上面的代码段将导致警告,因为分配给变量的值与变量的数据类型不匹配。

输出

Warning: A value of type 'String' cannot be assigned to a variable of type 'int' 

所有未初始化的变量的初始值为 null。这是因为 Dart 将所有值都视为对象。以下示例说明了这一点:

void main() { 
   int num; 
   print(num); 
}

输出

Null 

dynamic 关键字

未声明静态类型的变量隐式声明为 dynamic。变量也可以使用 dynamic 关键字代替 var 关键字进行声明。

以下示例说明了这一点。

void main() { 
   dynamic x = "tom"; 
   print(x);  
}

输出

tom

final 和 const

finalconst 关键字用于声明常量。Dart 阻止修改使用 final 或 const 关键字声明的变量的值。这些关键字可以与变量的数据类型一起使用,或者代替var 关键字。

const 关键字用于表示编译时常量。使用const 关键字声明的变量隐式为 final。

语法:final 关键字

final variable_name

final data_type  variable_name

语法:const 关键字

const variable_name

const data_type variable_name

示例 – final 关键字

void main() { 
   final val1 = 12; 
   print(val1); 
}

输出

12

示例 – const 关键字

void main() { 
   const pi = 3.14; 
   const area = pi*12*12; 
   print("The output is ${area}"); 
}

上面的示例使用const 关键字声明了两个常量piareaarea 变量的值是编译时常量。

输出

The output is 452.15999999999997

注意 - 只有const 变量才能用于计算编译时常量。编译时常量是在编译时确定其值的常量。

示例

如果尝试修改使用final 或 const 关键字声明的变量,Dart 将抛出异常。以下示例说明了这一点:

void main() { 
   final v1 = 12; 
   const v2 = 13; 
   v2 = 12; 
}

上面给出的代码将抛出以下错误作为输出

Unhandled exception: 
cannot assign to final variable 'v2='.  
NoSuchMethodError: cannot assign to final variable 'v2=' 
#0  NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:178) 
#1      main (file: Test.dart:5:3) 
#2    _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) 
#3    _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)
广告

© . All rights reserved.