数据类型
- numbers (int, double)
- strings
- booleans (bool)
- lists
- sets
- maps
- runes
- symbols
var s1 = '''
You can create
multi-line strings like this one.
''';
var s2 = """This is also a
multi-line string.""";
字符串前加r可以创建raw string
var s = r'In a raw string, not even \n gets special treatment.';
List
var list = [1, 2, 3];
var constantList = const [1, 2, 3];
Dart 2.3支持...和...?(允许空)的方式向集合中插入集合
var list = [1, 2, 3];
var list2 = [0, ...list];
var list2;
var list3 = [0, ...?list2];
Dart 2.3支持使用if 或 for这样的语句判断来添加集合元素
var nav = [
'Home',
'Furniture',
'Plants',
if (promoActive) 'Outlet'
];
var listOfInts = [1, 2, 3];
var listOfStrings = [
'#0',
for (var i in listOfInts) '#$i'
];
Set
创建一个Set数组是用{}
var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
//创建一个空Set
var names = {};
// Set names = {}; // This works, too.
// var names = {}; // Creates a map, not a set.
set也支持上述提到的2.3添加集合元素的新特性... / ...? 及 if / for
Map
var gifts = {
// Key: Value
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
var gifts = Map();
gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';
Map也支持上述提到的2.3添加集合元素的新特性... / ...? 及 if / for
函数
Dart语言的函数声明使用{param1, param2, …} ,函数调用时也带声明时的参数名,调用参数无顺序性,选择性
void enableFlags({bool bold, bool hidden}) {...}
//call
enableFlags(bold: true, hidden: false);
// 可以加@reqiured限制必须参数
const Scrollbar({Key key, @required Widget child})
- 使用[]来包含可选参数
- 可以为参数设置默认值
- 支持函数式调用
void printElement(int element) {
print(element);
}
var list = [1, 2, 3];
// Pass printElement as a parameter.
list.forEach(printElement);
//支持匿名函数式调用
var list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
print('${list.indexOf(item)}: $item');
});
//如果只带一个参数,还可以用箭头来调用函数
list.forEach(
(item) => print('${list.indexOf(item)}: $item'));
操作符
- as 类型转换
- is 类型判断
- is! 类型非判断
- ??= 如果空赋值
- condition ? expr1 : expr2 三目表达式
- expr1 ?? expr2 如果空表达式
- .. 级联符号
querySelector('#confirm') // Get an object.
..text = 'Confirm' // Use its members.
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));
- ?. 非空调用
控制语句
条件
if-else
循环
- forEach
- for-in
candidates.forEach((candidate) => candidate.interview());
var collection = [0, 1, 2];
for (var x in collection) {
print(x); // 0 1 2
}
while / do-while
switch-case
dart的case分支不允许分支语句为空的情况,像这样是不允许的:
swich(condition) {
case "A":
case "B":
doSomething...;
}
Assert
assert(condition, optionalMessage)
Exception
- throw / rethrow
- on - catch
catch(e, s) e-exception, s-stacktrace - finally
类
dart是一门面向对象的语言,基于mixin的继承方式。
构造函数
- 无显示构造函数,会有一个默认空构造函数
- 构造函数语法糖
class Point {
num x, y;
Point(num x, num y) {
// There's a better way to do this, stay tuned.
this.x = x;
this.y = y;
}
}
//可以简写成
class Point {
num x, y;
// Syntactic sugar for setting x and y
// before the constructor body runs.
Point(this.x, this.y);
}
- 别名构造函数
class Point {
num x, y;
Point(this.x, this.y);
// Named constructor
Point.origin() {
x = 0;
y = 0;
}
}
构造函数不继承,子类想继承别名构造函数,需显示继承自己实现
- 构造函数继承使用:
class Person {
String firstName;
Person.fromJson(Map data) {
print('in Person');
}
}
class Employee extends Person {
// Person does not have a default constructor;
// you must call super.fromJson(data).
Employee.fromJson(Map data) : super.fromJson(data) {
print('in Employee');
}
}
- dart构造函数后面可以跟初始化数据,也是跟在 : 之后,初始化数据之间用逗号隔开
// Initializer list sets instance variables before
// the constructor body runs.
Point.fromJson(Map json)
: x = json['x'],
y = json['y'] {
print('In Point.fromJson(): ($x, $y)');
}
dart构造函数执行顺序:初始化列表->父类的无参构造函数->子类的无参构造函数
- 重定向构造函数
指向另一个真正要调用构造函数,有点类似于别名函数,只是它不具体有构造函数体,只是指向一个存在的构造函数,用:指向
class Point {
num x, y;
// The main constructor for this class.
Point(this.x, this.y);
// Delegates to the main constructor.
Point.alongXAxis(num x) : this(x, 0);
}
- 常量构造函数,使用const关键字
const ImmutablePoint(this.x, this.y);
- 工厂构造函数,使用factory关键字
class Logger {
final String name;
bool mute = false;
// _cache is library-private, thanks to
// the _ in front of its name.
static final Map _cache =
{};
factory Logger(String name) {
return _cache.putIfAbsent(
name, () => Logger._internal(name));
}
Logger._internal(this.name);
void log(String msg) {
if (!mute) print(msg);
}
}
函数
- getter/settter 这两个是特殊的函数方法,每个字段会默认实现这两个方法,你可以重写它们,使用get/set关键字
class Rectangle {
num left, top, width, height;
Rectangle(this.left, this.top, this.width, this.height);
// Define two calculated properties: right and bottom.
num get right => left + width;
set right(num value) => left = value - width;
}
- 抽象函数, abstract
- 操作符重写
class Vector {
final int x, y;
Vector(this.x, this.y);
Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
// Operator == and hashCode not shown. For details, see note below.
// ···
}
- 扩展函数
他妈,看了半天原来说的就是可以直接使用引入库的方法
import 'string_apis.dart';
...
print('42'.padLeft(5)); // Use a String method.
print('42'.parseInt()); // Use an extension method.
- 枚举类
enum Color { red, green, blue }
- mixin
添加特性到类中,复用类的代码,类似于多继承的概念,使用with关键字
class Musician extends Performer with Musical {
// ···
}
class Maestro extends Person
with Musical, Aggressive, Demented {
Maestro(String maestroName) {
name = maestroName;
canConduct = true;
}
}
如果被混合那个类只是单做为混合使用,可以用mixin代替前面的class关键字
Mixin还可以限定它的使用类,通用on关键字来定义
mixin MusicalPerformer on Musician {
// ···
}
异步
async-await
Future checkVersion() async {
var version = await lookUpVersion();
// Do something with version
}
async关键字修饰的方法返回值是一个Future类型
- 异步获取stream流中的数据,使用await for
Future main() async {
// ...
await for (var request in requestServer) {
handleRequest(request);
}
// ...
}
生成序列串的两种方式
- 同步方式,生成Iterable,用sync*标记方法,用yield返回数据
Iterable naturalsTo(int n) sync* {
int k = 0;
while (k < n) yield k++;
}
- 异步方式,生成Stream,用sync*标记方法,用yield返回数据
Stream asynchronousNaturalsTo(int n) async* {
int k = 0;
while (k < n) yield k++;
}
typedef
定义方法别名,使函数式方法调用更清晰,可以直接传递定义的方法别名而不要传递一串函数体
在dart语言中,方法也是跟string,number一样,属于一个对象,Function类型
typedef Compare = int Function(Object a, Object b);
class SortedCollection {
Compare compare;
SortedCollection(this.compare);
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
void main() {
SortedCollection coll = SortedCollection(sort);
assert(coll.compare is Function);
assert(coll.compare is Compare);
}
Metadata
元数据类型,类似java中的注解