携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情
Dart介绍
首先为什么学习Dart,是因为Flutter使用Dart语言进行开发的
Dart语言其中有不少Java、Kotlin 和Js的影子,如果你之前是Android开发者、前端开发者,那么掌握Dart语言就会相对得心应手
哪里可以写Dart
相信在上一篇你已经新建了一个全新的flutter项目,那么就可以在test目录下书写dart代码,示例如下:
变量
Dart中定义变量有两种方式,一种是显式声明,指定变量类型,另一种是动态语言的常用方式,不指定类型,由虚拟机自动推断
//显式指定类型
String name = "张三";
//动态推断
var address = "李四";
如果想中途改变变量的数据类型,可以使用dynamic或者object来定义变量
dynamic age = 1;
age = "1year";
Object type = "male";
type = 2;
常量
Dart中定义常量有两种方式,一种是final定义,一个final变量只能赋值一次,final是运行时常量,final定义常量时,其值可以是一个变量。另一种是const,const常量是编译时常量,其值必须时一个字面常量值。
final time = new DateTime.now();
const list = 3.14;
基本数据类型
数字类型
在dart中有int、double两种类型,均继承num类,相对于java而言,没有float、short、long等类型。
int total = 500;
double price = 2.3;
int weight = 2;
print(total / weight);
//dart 中的取整区别于java采用 dart 使用~/
print(total ~/ weight);
字符串类型
在dart 中字符串支持单引号、双引号、三引号以及$模版,这些与kotlin是一致的
String name = 'Hello world!';
String title = "Hello world!";
String des = """
Hello
wordld
""";
int value = 2;
String result = "Result $value";
布尔类型
Dart中的布尔类型同java一样,有false、true两个值,但不能使用0、非0、null、非null 来表达false、true。但与java不同的是,布尔类型默认值是null
bool success = true;
Object类型
在Dart中所有东西都是对象,继承于Object,可以使用Object定义任何变量,且可以修改类型
Object value = 3;
value = "Hello world";
dynamic类型
var声明的变量在未赋值之前就是dynamic类型,与Object类似,可以改变类型。区别在于Object会在编译阶段检查类型, dynamic不会在编译阶段检查类型
dynamic value = 3;
value = "Hello world";
集合类型
列表
dart中的list与kotlin有很大区别,没有严格区分为可变集合和不可变集合,使用上更像是js,你会感觉它更像是数组。
List<String> cityList = ['三亚', '西安', '北京'];
cityList.add('长春');
print(cityList[2]);
cityList.removeAt(1);
cityList.insert(1, '郑州');
//遍历:
for(var i = 0 ; i < cityList.length; i++) {
print(cityList[i]);
}
cityList.forEach((element) {
print(element);
});
for(var city in cityList) {
print(city);
}
while(cityList.iterator.moveNext()) {
print(cityList.iterator.current);
}
集合Set
Set和列表List的区别在于集合的元素是不能重复的
Set<String> cityList = {'三亚', '西安', '北京'};
cityList.add('长春');
//遍历方式
cityList.forEach((element) {
print(element);
});
for(var city in cityList) {
print(city);
}
while(cityList.iterator.moveNext()) {
print(cityList.iterator.current);
}
集合Map
集合Map和Kotlin类似,key-value形式存储,并且Map对象的key不能重复
Map<String, String> map = {'san_ya': '三亚', 'xi_an': '西安'};
//修改指定的key值
map['san_ya'] = '修改三亚';
//修改指定的key值
map.remove('san_ya');
//是否包含指定的key值
print(map.containsKey('san_ya'));
//是否包含指定的value值
print(map.containsValue('西安'));
//遍历map
map.forEach((key, value) {
print("key is $key,value is $value");
});
流程控制
for循环
for(var i = 0; i < cityList.length; i++) {
print(cityList[i]);
}
while循环
var index = 0;
while(index < cityList.length) {
print(cityList[index++]);
}
do-while循环
do {
print(cityList[index++]);
} while(index < cityList.length);
switch-case
Color getColor(String colorName) {
Color currentColor = Colors.blue;
switch (colorName) {
case "read":
currentColor = Colors.red;
break;
case "blue":
currentColor = Colors.blue;
break;
case "yellow":
currentColor = Colors.yellow;
break;
}
return currentColor;
}
运算符
算术运算符
| 名称 | 运算符 | 示例 |
|---|---|---|
| 加 | + | int result += 1 |
| 减 | - | int result -= 1 |
| 乘 | * | int result = 2 * 4 |
| 除 | / | int result = 3 / 5 |
| 整除 | ~/ | int result = 3 ~/ 5 |
| 取余 | % | int result = 3 % 5 |
逻辑运算符
| 名称 | 运算符 | 示例 |
|---|---|---|
| 或 | + | 2 > 1 || 2 < 3 |
| 与 | - | 1 < 2 && 2 < 3 |
| 非 | * | !(2> 1) |
位运算符
| 名称 | 运算符 | 示例 |
|---|---|---|
| 位与 | & | 1 & 1 |
| 位或 | | | 1 | 2 |
| 位非 | ~ | ~1 |
| 异或 | ^ | 1 ^ 2 |
| 左移 | << | 1 << 2 |
| 右移 | >> | 1 >> 2 |
空安全符
| 运算符 | 解释 |
|---|---|
| result = expr1 ?? expr2 | 若expr1为null, 返回expr2的值,否则返回expr1的值 |
| expr1 ??= expr2 | 若expr1为null, 则把expr2的值赋值给expr1 |
| result = expr1?.value | 若expr1为null, 就返回null,否则就返回expr1.value的值 |
异常
dart中的异常捕获与java、kotlin类似, 使用的是try-catch-finally, 对特定异常的捕获使用on关键字
int result = 0;
try {
result = num ~/ 0;
} catch (e) {//捕获到IntegerDivisionByZeroException
print(e.toString());
} finally {
print('$result');
}
函数
了解了上述的数据类型和运算符之后,在函数中就可以将其实际的运用起来
函数的基本用法
num sum(num a, num b) {
return a + b;
}
函数参数列表及规则
//num a, num b, num c, num d 最普通的传参: 调用时,参数个数和参数顺序必须固定
func1(num a, num b, num c, num d) {
print(a + b + c + d);
}
//[num a, num b, num c, num d]传参: 调用时,参数个数不固定,但是参数顺序需要一一对应, 不支持命名参数
func2([num a, num b, num c, num d]) {
print(a + b + c + d);
}
//{num a, num b, num c, num d}传参: 调用时,参数个数不固定,参数顺序也可以不固定,支持命名参数,也叫可选参数,是dart中的一大特性,这就是为啥Flutter代码那么多可选属性,大量使用可选参数
func3({num a, num b, num c, num d}) {
print(a + b + c + d);
}
//num a, num b, {num c, num d}传参: 调用时,a,b参数个数固定顺序固定,c,d参数个数和顺序也可以不固定
func4(num a, num b, {num c, num d}) {
print(a + b + c + d);
}
函数默认参数
func({num a, num b, num c, num d = 100}) {//d就是默认值参数,给的默认值是100
print(a + b + c + d);
}
函数类型及高阶函数
dart的函数其实是一种类型Function, 类似于Kotlin, 可以作为函数参数传递
main() {
Function square = (a) {
return a * a;
};
Function square2 = (a) {
return a * a * a;
};
add(3, 4, square, square2)
}
num add(num a, num b, [Function op, Function op2]) {
//函数作为参数传递
return op(a) + op2(b);
}
面向对象-类
在dart一切都是对象,所以学会面向对象的思想很重要
类的定义
abstract class Person {
String name;
int age;
double height;
Person(this.name, this.age, this.height);
Person(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
}
class Student extends Person {//和Java一样同时使用extends关键字表示继承
Student(String name, int age, double height, double grade): super(name, age, height);//在 Dart里:类名(变量,变量,...) 是构造函数的写法, :super()表示该构造调用父类,这里构造时传入三个参数
}
get和set
abstract class Person {
String _name;
final int _age;
Person(this._name, this._age); //这是上述简写形式
//使用set关键字 计算属性 自定义setter访问器
set name(String name) => _name = name;
//使用get关键字 计算属性 自定义getter访问器
bool get isStudent => _age > 18;
}
到目前为止已经了解了Dart的基础语法,Dart的内容还有很多,后续会逐步的了解学习。下一步是时候去聊关于Flutter的布局、状态管理等等。