2. Variables and Data Types
2.1. Variables and constants
Variable popular to say that amount may change, the role is used to store data, you can put a variable considered as a fruit basket, which can be installed apples, pears, bananas, etc., the constant is a fixed value, and variables are relatively the variables can change, constant change is not
1. declare variables
In the dart in the var to declare a variable, and this variable is declared as js
void main() {
var num = 10;
print(num); // 10
}
Note: There is no assignment to a variable, the default is null
void main() {
var num;
print(num); // null
}
Variables can be used to declare a final keyword can only be assigned once
void main() {
final num = 10;
print(num);
// num = 30;
// print(num); // 把这两行注释打开会报错
}
2. constant declaration
Constant declaration requires the use of the const keyword, this const and es6 in similar
void main() {
const num = 10;
print(num);
num = 30; // 报错
}
Const and the difference 3.final
2.2. Data Types
Data type dart provided are the following:
1. 数字类型-numbber 2. 字符串类型-string
3. 布尔类型-Boolean 4. 列表-list
5. Map 6. Runes
7、Symbols
1. Digital type (number)
It comprises a numeric integer (int) and float (double), when the defined variables can be predetermined type
void main() {
// num是整型和浮点型的总称, 这个时候变量a里面既可以存整型也可以存浮点型
num a = 20;
print(a);
a = 20.5;
print(a);
}
void main() {
// int表示定义整型,这个时候里面不能存浮点型
int a = 20;
print(a);
a = 20.5; // 报错
print(a);
}
void main() {
double a = 20.5;
print(a);
a = 20; // 没报错
print(a); // 20.0
}
2. Type String (String)
String can be defined in various ways, including single and double quotation marks, three marks, like the original string
void main() {
// 单引号形式
String str1 = 'hello nodeing!!';
// 双引号形式
String str2 = "hello nodeing!!!";
// 三引号形式,可以创建多行字符串
String str3 = '''
<div>
<h1>hello nodeing!!</h1>
</div>
''';
// 定义原始字符串
String str4 = r'hello \n nodeing!!!';
// 没有使用原始字符串定义
String str5 = 'hello \n nodeing!!!';
print(str1);
print(str2);
print(str3);
print(str4);
print(str5);
}
The above code should be noted that, because no str5 original string is defined, it \ n will be treated as a carriage return line
3. Boolean type (Boolean)
Boolean type is very simple, only two values, true and false
void main() {
bool a = true;
bool b = false;
print(a);
print(b);
}
4.list list
js list and in an array of similar, looks all the same
void main() {
// 创建一个list
var lis = [1, 2, 3];
print(lis);
// 通过类的方式创建
var lis2 = new List();
print(lis2);
// 创建一个不可变的列表
var lis3 = const [1, 2, 3];
lis3[0] = 2; // 报错
}
5.Map type
Map is that some type of key-value pairs
void main() {
// 创建一个list
var mp = {'name': 'xiaoqiang', 'age': 18};
print(mp);
// 通过类的方式创建
var mp2 = new Map();
print(mp2);
// 创建一个不可变的Map
var mp3 = const {'name': 'xiaosan', 'age': 30};
// 获取值
print(mp3['name']);
mp3['name'] = 'xiaosi'; // 报错
}
Screw classroom video lessons Address: http://edu.nodeing.com