目录
- Hello world!
- Variables
- Control Flow Statement
- Functions
- Comments
- Imports
- Classes
- Inheritance
- Mixins
- Interface and Abstract class
- Async
- Exception
1. Hello world!
每个应用都有一个main()函数,Dart的主函数如下:
void main() {
print('Hello, World!');
}
2. Variables
Dart语言是类型安全的强类型语言,因此,在定义属性时需要定义类型。
如果属性有初始化值时,Dart会默认推测出此属性的类型,因此不需要显式地声明类型;
如果属性没有初始化值,则必须要为属性显式声明类型。
var name = 'Voyager I';
var year = 1977;
var antennaDiameter = 3.7;
var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
var image = {
'tags': ['saturn'],
'url': '//path/to/saturn.jpg'
};
3. Control Flow Statement
Dart的控制流类似Java、JavaScript、Kotlin等语言,这里不再累述!
if (year >= 2001) {
print('21st century');
} else if (year >= 1901) {
print('20th century');
}
for (var object in flybyObjects) {
print(object);
}
for (int month = 1; month <= 12; month++) {
print(month);
}
while (year < 2016) {
year += 1;
}
4. Functions
Dart的函数支持
int fibonacci(int n) {
if (n == 0 || n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
var result = fibonacci(20);
Dart使用 => 表示拥有单行表达式的函数的简写的指示器
flybyObjects.where((name) => name.contains('turn')).forEach(print);
5. Comments
Dart的注释使用比较新颖!
// This is a normal, one-line comment.
/// This is a documentation comment, used to document libraries,
/// classes, and their members. Tools like IDEs and dartdoc treat
/// doc comments specially.
/* Comments like these are also supported. */
6. Imports
Dart的导包类似JavaScript
// Importing core libraries
import 'dart:math';
// Importing libraries from external packages
import 'package:test/test.dart';
// Importing files
import 'path/to/my_other_file.dart';
7. Classes
Dart定义类、构造器、属性
定义一个拥有两个构造器,一个函数,三个属性的类(注意下面的定义两个构造器的新颖方式)
class Spacecraft {
String name;
DateTime launchDate;
// Constructor, with syntactic sugar for assignment to members.
Spacecraft(this.name, this.launchDate) {
// Initialization code goes here.
}
// Named constructor that forwards to the default one.
Spacecraft.unlaunched(String name) : this(name, null);
int get launchYear =>
launchDate?.year; // read-only non-final property
// Method.
void describe() {
print('Spacecraft: $name');
if (launchDate != null) {
int years =
DateTime.now().difference(launchDate).inDays ~/
365;
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}
-----
使用这个类
var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
voyager.describe();
var voyager3 = Spacecraft.unlaunched('Voyager III');
voyager3.describe();
8. Inheritance
Dart的继承
Dart的继承不同与Java语言(Dart的每个类都默认是接口;Dart不仅可以实现”单继承“还可以实现“多继承”)
class Orbiter extends Spacecraft {
num altitude;
Orbiter(String name, DateTime launchDate, this.altitude)
: super(name, launchDate);
}
9. Mixins
Dart的多继承通过“extends with”和“implements”实现,请往下看!
定义一个类
class Piloted {
int astronauts = 1;
void describeCrew() {
print('Number of astronauts: $astronauts');
}
}
多继承
class PilotedCraft extends Spacecraft with Piloted {
// ···
}
10. Interface and Abstract class
Dart没有单独定义接口的关键词,Dart的每个类默认都是接口,都可以使用implements被实现
Dart的抽象类类似Java
定义一个类/一个接口
class MockSpaceship implements Spacecraft {
// ···
}
定义抽象类
abstract class Describable {
void describe();
void describeWithEmphasis() {
print('=========');
describe();
print('=========');
}
}
11. Async
Dart的异步类似JavaScript、Kotlin等语言!
const oneSecond = Duration(seconds: 1);
// ···
Future<void> printWithDelay(String message) async {
await Future.delayed(oneSecond);
print(message);
}
12. Exception
Dart的异常类似Java、Kotlin等语言,如下图
主动抛出异常
if (astronauts == 0) {
throw StateError('No astronauts.');
}
捕获异常、处理异常 类似Java,不同的是多了on (on 和 catch的区别是on没有参数,catch有参数)
try {
for (var object in flybyObjects) {
var description = await File('$object.txt').readAsString();
print(description);
}
} on IOException catch (e) {
print('Could not describe object: $e');
} finally {
flybyObjects.clear();
}
未完待续。。。