數(shù)據(jù)類型
在 Dart 里是強(qiáng)類型的薄货,也有自動推斷類型的機(jī)制。
在 Dart 里定義變量使用有 var碍论、const谅猾、dynamic、Object鳍悠、類型等方式税娜。對于函數(shù)而言,并不需要寫 function 關(guān)鍵字藏研,而讓它有函數(shù)應(yīng)有的外形即可敬矩。
// 基本類型
var name = 'Voyager I';
var antennaDiameter = 3.7;
const image = {
'tags': ['Jupiter', 'Saturn', 'Uranus', 'Neptune'],
'url': '//path/to/saturn.jpg'
};
// 函數(shù)類型
String sayHello(var name) {
return 'Hello $name!';
}
// 箭頭函數(shù)
var add = (a, b) => a + b;
// 類似 Promise
Future sum(num a, num b) async {
return await add(a, b);
}
// main 函數(shù)
void main() async {
print(sayHello(name)); // Hello Voyager I!
print(max(1, 2)); // 2
sum(1, 2).then((res) => print(res)); // 3 (類似 Promise)
}
Object name1 = "小明";
dynamic name2 = "老王";
dynamic 是任意的意思,它與 var 不同遥倦,var 會自動推斷類型從而得出一個確定類型谤绳,而 dynamic 可以表示任意占锯,相對于 Typescript 中的 any。
Dart 在聲明時有以下幾個基本類型:number缩筛、string消略、boolean、list瞎抛、map艺演、rune、symbol
int x = 1;
double y = 1.1;
num z = 1.2;
String x = 'abc';
enum Color { red, green, blue }; // 枚舉類型
const msPerSecond = 1000;
bool flag = false;
var list = [1, 2, 3];
List arr = [1, 2, 3];
List<String> names = ['a', 'b', 'c']; // 泛型
var constantList = const [1, 2, 3];
Map nobleGases = const {
2: 'helium',
10: 'neon',
18: 'argon',
};
var gifts = {
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
print(gifts['first']);
// 在 Dart 里桐臊,對象是 Map 不能用 . 的形式訪問胎撤,只能用 [] 的形式訪問。
函數(shù)
Dart 的函數(shù)支持函數(shù)聲明断凶、函數(shù)字面量伤提、箭頭函數(shù)、函數(shù)表達(dá)式认烁、匿名函數(shù)肿男。
int add(int a, int b) {
return a + b;
}
// 類型可省略
add(a, b) {
return a + b;
}
// 箭頭函數(shù)
var add = (a, b) => a + b;
int add(int a, int b) => a + b;
// 可選參數(shù),使用 [] 限定
int add(int a, int b, [int c = 1, int d = 2]) => a + b + c + d;
// 顯示指定參數(shù)名稱却嗡,默認(rèn)參數(shù)
int add({ int a = 1, int b = 2 }) {
return a + b;
}
add(a: 1, b: 2);
// 回調(diào)函數(shù)
var list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
print('${list.indexOf(item)}: $item');
});
// 回調(diào) + 箭頭
list.forEach((item) => print(item));
// 閉包
Function makeAdder(int addBy) {
return (int i) => addBy + i;
}
操作符
操作符包括了:expr++舶沛、expr--、()窗价、[]如庭、.、?撼港、
等坪它,基本和 ES6 一致,除了沒有 === 的判斷餐胀。
例外有三個特色的操作:is哟楷、as瘤载、is?
否灾。
is
用于判斷類型,as
用于續(xù)言鸣奔、is?
與 is
相反墨技。
if (emp is Person) {
// Type check
emp.firstName = 'Bob';
}
(emp as Person).firstName = 'Bob';
級聯(lián)符號(..):允許您在同一個對象上進(jìn)行一系列操作。除了函數(shù)調(diào)用之外挎狸,還可以訪問同一對象上的字段扣汪。這通常會為您節(jié)省創(chuàng)建臨時變量的步驟,并允許您編寫更流暢的代碼锨匆。
var gifts = {
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
getGifts() {
return gifts;
}
// 不使用級聯(lián)符號
var g = getGifts();
g.first = 1;
g.second = 2;
g.fifth = 3;
// 使用級聯(lián)符號
getGifts()
..first = 1
..second = 2
..fifth = 3;
級聯(lián)符號對于時引用操作的是非常有用崭别。
控制流程
Dart 的控制流程支持:if冬筒、if-else、for茅主、while舞痰、do-while、switch诀姚、try-catch-finally
if (isRaining()) {
// ...
} else if (isSnowing()) {
// ...
} else {
// ...
}
var message = new StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
message.write('!');
}
var collection = [0, 1, 2];
for (var x in collection) {
print(x); // 0 1 2
}
類結(jié)構(gòu)
Dart 的類支持繼承响牛、靜態(tài)方法、接口赫段、構(gòu)造函數(shù)呀打、重載操作符、抽象類糯笙、接口類贬丛、 mixins等。
Dart 的類不支持什么 public给涕、private 這些瘫寝。_method 下劃線代表私有方法。
lass X {
num x, y;
X(x, y) {
this.x = x;
this.y = y;
}
void say() {
print(this.x + this.y);
}
}
class Point extends X {
num x;
num y;
final int k = 1; // 無法被實(shí)例修改值
static const int initialCapacity = 16; // 靜態(tài)常量
// 靜態(tài)方法
static add() {
// ...
}
// 構(gòu)造函數(shù)稠炬,用 :super(arg) 調(diào)用父類的構(gòu)造函數(shù)
// 等效 => Point(this.x, this.y): super(x, y);
Point(num x, num y): super(x, y) {
super.say(); // 調(diào)用父類的方法
this.x = x;
this.y = y;
}
// 命名構(gòu)造函數(shù)(覺得構(gòu)造函數(shù)長的丑焕阿,也可以命名哦)
// var p = new Point.origin();
Point.origin() {
x = 0;
y = 0;
}
// getter、setter 函數(shù)
get xx => this.x;
set xx(v) => this.x = xx;
// 重寫父類的方法首启,其實(shí)不佳 @override 也可以
@override
void say() {
// ···
}
}
Dart 還支持重載操作符暮屡。
// 重載操作符
class Vector {
final int x, y;
const Vector(this.x, this.y);
/// Overrides + (a + b).
Vector operator +(Vector v) {
return new Vector(x + v.x, y + v.y);
}
/// Overrides - (a - b).
Vector operator -(Vector v) {
return new Vector(x - v.x, y - v.y);
}
}
Dart 中的實(shí)現(xiàn)接口類。
class Impostor implements Person {
get _name => '';
String greet(String who) => 'Hi $who. Do you know who I am?';
}
Dart 能支持 mixins毅桃,使用 with 關(guān)鍵字褒纲。
class Musician extends Performer with Musical {
// ···
}
泛型
Dart 支持泛型哦。
var names = <String>['Seth', 'Kathy', 'Lars'];
var pages = <String, String>{
'index.html': 'Homepage',
'robots.txt': 'Hints for web robots',
'humans.txt': 'We are people, not machines'
};
var names = new List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
names.add(42); // Error
print(names is List<String>); // true
// 泛型函數(shù)
T first<T>(List<T> ts) {
T tmp = ts[0];
return tmp;
}
// 泛型類
abstract class Cache<T> {
T getByKey(String key);
void setByKey(String key, T value);
}
模塊
Dart 的模塊導(dǎo)入钥飞。
// 全部導(dǎo)入莺掠,并且是全局變量
import 'dart:math';
max(1, 2);
// 別名
import 'dart:math' as math;
math.max(1, 2);
// 只導(dǎo)入部分
import 'dart:math' show min;
min(1, 2);
// 懶加載,類似 ES6 的 import()
import 'dart:math' deferred as math;
Future greet() async {
await math.max(1, 2);
}
導(dǎo)出模塊读宙,創(chuàng)建一個 myMath.dart 文件彻秆。
int max(int a, int b) {
return a > b ? a : b;
}
int _min(int a, int b) {
return a < b ? a : b;
}
Dart 的導(dǎo)出默認(rèn)是帶下劃線為私有,其他為公有结闸。
import './myMath.dart' as math;
math.max(1, 2);
異步編程
在 ES6 與異步相關(guān)的就是 Promise唇兑、async、await桦锄。而在 Dart 則是 Future扎附、async、await结耀。
Dart庫充滿了返回 Future 或 Stream 對象的函數(shù)留夜。這些功能是異步的:它們在設(shè)置可能耗時的操作(例如 I/O)之后返回匙铡,而不等待該操作完成。 在 async 和 await 關(guān)鍵字支持異步編程碍粥,讓你寫異步代碼看起來類似于同步代碼慰枕。
使用 async/await 之前需要引入 dart:async 模塊。
import 'dart:async';
Future<String> lookUpVersion() async => '1.0.0';
Future main() async {
await for (var request in requestServer) {
handleRequest(request);
}
}
也支持 then即纲,catchError 等具帮。
void getIPAddress() {
final url = 'https://httpbin.org/ip';
HttpRequest.request(url).then((value) {
print(json.decode(value.responseText)['origin']);
}).catchError((error) => print(error));
}
// 也可以這樣寫
Future<String> getIPAddress() async {
final url = 'https://httpbin.org/ip';
var request = await HttpRequest.request(url);
String ip = json.decode(request.responseText)['origin'];
return ip;
}
類似 setTimeout 的操作。
// 等待 2000ms
await new Future.delayed(const Duration(milliseconds: 2000));
// 或者
new Future.delayed(const Duration(milliseconds: 2000)).then(() {
// ...
});
JSON處理
json 在 JavaScript 里是一個非常有優(yōu)勢的處理低斋,因?yàn)?json 本身延至于 JavaScript蜂厅。
在 Dart 里處理 json 有兩個 API 可用:encode(序列化) 和 decode(反序列化)。
// 把對象轉(zhuǎn)為 json 字符串
var jsonstr = json.encode([1, 2, { "a": null }]);
// 把 json 字符串轉(zhuǎn)為對象
var decoded = json.decode('["foo", { "bar": 499 }]');
正則表達(dá)式
正則使用的是 RegExp 對象膊畴。
RegExp exp = new RegExp(r"(\w+)");
// 返回正則表達(dá)式匹配項(xiàng)的可迭代對象
exp.allMatches("abc def ghi");
// 搜索并返回第一個匹配項(xiàng)掘猿,沒有則返回null
exp.firstMatch("");
// 正則表達(dá)式是否找到匹配項(xiàng)
exp.hasMatch("as");
// 從第幾個字符開始匹配正則表達(dá)式
exp.matchAsPrefix("ab cd", 3);
// 返回正則表達(dá)式的第一個匹配字符串
exp.stringMatch("abc de");
// 返回正則表達(dá)式的字符串表示
exp.toString();