Get Dart language for Android and iOS at the same time (2): Variables and constants

1. Define and use variables

Although Dart is a static language, it still has dynamic characteristics. So there are two ways to define variables.

  • Use data types to define variables

  • Use var to define variables

 

In Dart language, the data type is placed in front of the variable, and the format is as follows:

数据类型  变量名;

 In the Dart language, each statement must be followed by a semicolon (;), so you must add a semicolon when you define a variable. For example, the following code defines a variable of integer type and a variable of string type.

int num;      // 整数类型的变量
String s;     // 字符串类型的变量

 When defining variables, you can assign values ​​to variables at the same time, which is also called initialization, so you can use the following code to assign values ​​to num and s.

int num = 20;
String s = "hello world";

 If the data type is specified when the variable is defined, it means that the data type of the variable cannot be changed. For example, the num variable has been defined as an int type in the above code, then num will always be of the int type, and other variables cannot be assigned The value of the type.

Since everything in the Dart language is an object, if the variable is not initialized when it is defined, the default value of the variable is null.

Another way to define variables is to use the var keyword, the code is as follows:

var num = 20;          // num被自动识别为int类型的变量
var value;             // 由于value在定义时没有被初始化,所以value的数据类型是dynamic

The above two lines of code use var to define two variables, but these two variables are different. Since the num variable has been initialized when it is defined, the data type of num will be automatically identified according to the initialized value. Obviously, 20 belongs to the value of type int, so the data type of the num variable is int, and the data type of the variable is directly specified Similarly, the data type of the num variable will be permanently fixed and cannot be changed later. But the value is different. Since the value variable is not initialized and the data type is not specified when the value variable is defined, the data type of the value is recognized as dynamic. This is a special data type in the Dart language. With dynmaic, Dart can be easily dynamic. If the Dart compiler encounters a variable of the dynamic data type, it will not perform any type detection on the variable, which is equivalent to using a variable in JavaScript. However, if members (such as properties, methods, etc.) that do not exist in the variable are called, an exception will be thrown at runtime. But dynamic provides a solution to avoid this exception. The detailed usage of dynamic will be introduced in depth in later chapters.

In summary, in the Dart language, if a data type is specified for a variable, the variable is static, and the data type of the variable can never be changed. If the data type of the variable is dynamic, the variable is dynamic. You can assign any value to this variable. Let the variable be static type and dynamic type respectively by the following two ways.

(1) Statically typed variables

(1) Explicitly specify the data type of the variable, such as int num;

(2) Use var to define a variable, but initialize the variable when it is defined, and the expression of the initialized variable is not of dynamic type. Such as var value = 20;

 

(2) Variables of dynamic type

  • Use var to define variables, and the variables are not initialized at the time of definition. Even if a value is assigned to the variable later, the variable is still a dynamic variable, such as var value;

  • Use the dynamic type directly to define variables, such as dynamic value;

 

This example demonstrates various ways of defining and using variables.

void main() {
  var name = "Bill";        // String类型变量
  var value1 = 20;         // int类型变量
  int value2 = 30;         // int类型变量
  print(name);             // 输出Bill
  print(value1 + value2);   // 输出50
  // 在Dart中一切都是对象,如果未初始化变量,变量的默认值就是null
  var value;               // dynamic类型变量
  int value3;              // int类型变量
  print(value);            // 输出null 
  print(value3);           // 输出null
  String s;
  // 条件为true
  if(s == null) {
    print("NULL");
  }
}

 The running result is shown in Figure 1.

Figure 1 Define and use variables

2. Define and use constants

The definition of constants is similar to that of variables, except that you need to use const or final to define constants. These two keywords are equivalent to the effect of var on variables. The following is the basic method of defining constants.

final username = '李宁';
const value = 1234;

In the above code, username and value are two constants. Neither of these two constants specify the data type. However, since the Dart language requires constants to be initialized when they are defined, there will be an initialization expression on the right side of all defined constants. The Dart compiler will use this initialization expression to automatically identify the data type of the constant. In the above example, username is recognized as String type and value is recognized as int type.

When defining a constant, you can also specify its data type explicitly, the code is as follows:



final String username = '李宁';
const int value = 1234;

 Constants can only be initialized once at the time of definition and cannot be assigned during use, so the following code cannot be compiled.

username = '小明';          // 无法给常量赋值,会出现编译错误
value = 4321;              // 无法给常量赋值,会出现编译错误

Then some readers may ask, why define constants to provide two keywords (const and final)? There is a certain difference between using these two keywords to define constants. const is a compile-time constant, and final is a runtime constant. The following explains what are compile-time constants and what are runtime constants.

  • Compile-time constant: A constant that is automatically calculated by the Dart compiler at compile time, that is, regardless of whether the constant is initialized as a value or an expression, the Dart compiler will calculate the expression into a value. In other words, this constant no matter what the initialization expression is, it will eventually be a value in memory. Therefore, the efficiency of using this constant is particularly high.

  • Run-time constant: This kind of constant is similar to a variable. The value of the technical constant is initialized every time the constant is used, so the efficiency of using this variable is low.

Since the compile-time constant will automatically calculate the value of the initialization expression when compiling the code, it means that each part of the initialization expression must obtain a specific value at compile time. This requires that the initialization expression can only be composed of values ​​or other compile-time constants, not variables, runtime constants, and functions. Because the value of these elements can only be obtained when the program is running, and the program is not yet running at compile time, the initialization expression of the constant at compile time cannot be composed of these elements.

The initialization expression of the runtime constant is similar to the initialization expression of the variable.

See the code below for the usage of const and final.

const m = 20;              // 编译时常量
const n = m + 30;          // 编译时常量
final k = 40;              // 运行时常量
const w = k + 20;          // 编译错误,因为编译时常量的初始化表达式只能由值和编译时常量组成

3. Constant List and List Constant

Constants can also be used to define lists. List is a built-in data type of Dart language. The detailed usage of list will be introduced in depth in later chapters. This section only introduces the use of final and const to define constant lists and list constants. So what is the difference between these two lists?

  • Constant list: means that every element in the list is a constant, but the list itself may be a constant or a variable. If the list itself is a variable, and the list elements are constants, it means that each element of the list cannot be modified, but the list variable can be assigned again.

  • List constant: The list itself is a constant. For such constants, each element in the list is also a constant. For this kind of list, neither the list itself nor the elements in the list can be changed.

 

When defining a constant list, you can add const before the initial value of the list (final cannot be used) or not. When defining a list constant, you can use const or final.

This example demonstrates the definition and usage of constants, as well as the definition and usage of constant lists and list constants.

void main() {
  final username = '李宁';
  const password = '1234';
  // username = "abc";          // 编译错误,不能为常量赋值
  // password = "1234";         // 编译错误,不能为常量赋值
 
  const n = 20;       
  final x1 = n *2 + 20;
  const x2 = n * 2 + 20;         // 自动计算,x2实际上存储的是60
  const x3 = x2 * 2;
 
  print(x2);
  print(x3);
 
  var values1 = const [1,2,3];      // 定义一个常量列表
 
  print(values1);
  values1 = [5,6,7];                // 列表本身是变量,所以可以重新设置列表的值
  print(values1[1]);
  // values[1] = 4;                 // 不会有编译错误,但会抛出运行时异常
 
  final values2 = const["a","b"];   // 定义列表常量
  // values2 = ["b","c"];           // 编译错误
  // values2[1] = "x";              // 运行时错误
 
  const values3 = [5,6];            // 定义一个列表常量
  // values3[1] = 4;                 // 运行时错误
}

The running result is shown in Figure 2.

Figure 2 Constants and lists

Past review:

Get the Dart language for Android and iOS at the same time (1): A preliminary study of Dart

If you are interested in this article, you can add teacher Li Ning's WeChat public account (unitymarvel):

Follow the official account of Geek Origin to get more free technical videos and articles.

 

Guess you like

Origin blog.csdn.net/nokiaguy/article/details/107777349