一、Object(對象)
- Dart 是一個面向?qū)ο缶幊陶Z言兰伤。
- Dart支持基于 mixin 的繼承機制(相當(dāng)于多繼承内颗,但不是多繼承,Dart語言是單繼承医清,mixin只是實現(xiàn)類似多繼承的一種方式)起暮。
- 每個對象都是一個類的實例,所有的類都繼承于 Object.会烙。
- 所有的類有同一個基類:
Object
负懦。 - 使用
new
關(guān)鍵字和構(gòu)造函數(shù)來創(chuàng)建新的對象。 構(gòu)造函數(shù)名字可以為 ClassName 或者 ClassName.identifier柏腻。例如:
var jsonData = JSON.decode('{"x":1, "y":2}');
// Create a Point using Point().
var p1 = new Point(2, 2);
// Create a Point using Point.fromJson().
var p2 = new Point.fromJson(jsonData);
- 使用點
.
來引用對象的變量或者方法:
var p = new Point(2, 2);
// Set the value of the instance variable y.
p.y = 3;
// Get the value of y.
assert(p.y == 3);
// Invoke distanceTo() on p.
num distance = p.distanceTo(new Point(4, 4));
- 使用
?.
來替代.
可以避免當(dāng)左邊對象為null
時候 拋出異常(有點類似swift語言)
// If p is non-null, set its y value to 4.
p?.y = 4;
- 有些類提供了常量構(gòu)造函數(shù)纸厉。使用常量構(gòu)造函數(shù) 可以創(chuàng)建編譯時常量,要使用常量構(gòu)造函數(shù)只需要用
const
替代new
即可
var p = const ImmutablePoint(2, 2);
- 兩個一樣的編譯時常量其實是 同一個對象
var a = const ImmutablePoint(1, 1);
var b = const ImmutablePoint(1, 1);
assert(identical(a, b)); // They are the same instance!
- 可以使用 Object 的
runtimeType
屬性來判斷實例 的類型五嫂,該屬性 返回一個 Type 對象颗品。
var a = 'test';
var b = 5;
var c = [56,3,4,6,0];
var d = {
'key1':'value1',
'key2':'value2'
};
// The type of a is String
print('The type of a is ${a.runtimeType}');
// The type of a is int
print('The type of a is ${b.runtimeType}');
// The type of a is List<int>
print('The type of a is ${c.runtimeType}');
// The type of a is _InternalLinkedHashMap<String, String>
print('The type of a is ${d.runtimeType}');
二、Instance variables(實例化變量)
- 在類定義中沃缘,所有沒有初始化的變量都會被初始化為
null
躯枢。
class Point {
num x; // Declare instance variable x, initially null.
num y; // Declare y, initially null.
num z = 0; // Declare z, initially 0.
}
main() {
/* 每個實例變量都會自動生成一個 getter 方法(隱含的)。
Non-final 實例變量還會自動生成一個 setter 方法槐臀。
*/
var point = new Point();
point.x = 4; // Use the setter method for x.
assert(point.x == 4); // Use the getter method for x.
assert(point.y == null); // Values default to null.
}
三锄蹂、Constructors(構(gòu)造函數(shù))
注意:Constructors aren’t inherited(構(gòu)造函數(shù)不會繼承)
子類不會繼承超類的構(gòu)造函數(shù)。 子類如果沒有定義構(gòu)造函數(shù)水慨,則只有一個默認(rèn)構(gòu)造函數(shù) (沒有名字沒有參數(shù))得糜。如果你希望子類也有超類一樣的命名構(gòu)造函數(shù), 你必須在子類中自己實現(xiàn)該構(gòu)造函數(shù)晰洒。
3.1.Default constructors(默認(rèn)構(gòu)造函數(shù))
如果你沒有定義構(gòu)造函數(shù)朝抖,則會有個默認(rèn)構(gòu)造函數(shù)。 默認(rèn)構(gòu)造函數(shù)沒有參數(shù)谍珊,并且會調(diào)用超類的沒有參數(shù)的構(gòu)造函數(shù)治宣。
- 聲明一個和類名相同的函數(shù),來作為類的構(gòu)造函數(shù)砌滞。
class Point {
num x;
num y;
Point(num x, num y) {
// There's a better way to do this, stay tuned.
this.x = x;
this.y = y;
}
}
- this 關(guān)鍵字指當(dāng)前的實例炼七。
注意: 只有當(dāng)名字沖突的時候才使用
this
。否則的話布持, Dart 代碼風(fēng)格樣式推薦忽略this
。
class Point {
num x;
num y;
// Point(num x, num y) {
// // There's a better way to do this, stay tuned.
// this.x = x;
// this.y = y;
// }
Point(num param1, num param2) {
// 實例變量和參數(shù)名不沖突市陕悬,推薦忽略 this
x = param1;
y = param2;
}
}
- 把構(gòu)造函數(shù)參數(shù)賦值給實例變量的場景太常見了题暖, Dart 提供了一個語法糖來簡化這個操作:
class Point {
num x;
num y;
// Syntactic sugar for setting x and y
// before the constructor body runs.
Point(this.x, this.y);
}
3.2.Named constructors(命名構(gòu)造函數(shù))
使用命名構(gòu)造函數(shù)可以為一個類實現(xiàn)多個構(gòu)造函數(shù), 或者使用命名構(gòu)造函數(shù)來更清晰的表明你的意圖:
class Point {
num x;
num y;
Point(this.x, this.y);
// Named constructor
Point.fromJson(Map json) {
x = json['x'];
y = json['y'];
}
}
3.3.Invoking a non-default superclass constructor(調(diào)用超類構(gòu)造函數(shù))
默認(rèn)情況下,子類的構(gòu)造函數(shù)會自動調(diào)用超類的 無名無參數(shù)的默認(rèn)構(gòu)造函數(shù)胧卤。 超類的構(gòu)造函數(shù)在子類構(gòu)造函數(shù)體開始執(zhí)行的位置調(diào)用唯绍。 如果提供了一個 initializer list(初始化參數(shù)列表) ,則初始化參數(shù)列表在超類構(gòu)造函數(shù)執(zhí)行之前執(zhí)行枝誊。 下面是構(gòu)造函數(shù)執(zhí)行順序:
- initializer list(初始化參數(shù)列表)
- superclass’s no-arg constructor(超類的無名構(gòu)造函數(shù))
- main class’s no-arg constructor(主類的無名構(gòu)造函數(shù))
如果超類沒有無名無參數(shù)構(gòu)造函數(shù), 則你需要手工的調(diào)用超類的其他構(gòu)造函數(shù)。 在構(gòu)造函數(shù)參數(shù)后使用冒號 (:
) 可以調(diào)用 超類構(gòu)造函數(shù)疟暖。
下面的示例中贪嫂,Employee 類的構(gòu)造函數(shù)調(diào)用 了超類 Person 的命名構(gòu)造函數(shù)。
class Person {
String firstName;
Person.fromJson(Map data) {
print('in Person');
}
}
class Employee extends Person {
// Person 沒有默認(rèn)構(gòu)造函數(shù)
// 必須調(diào)用 super.fromJson(data).
Employee.fromJson(Map data) : super.fromJson(data) {
print('in Employee');
}
}
main() {
var emp = new Employee.fromJson({});
// Prints:
// in Person
// in Employee
if (emp is Person) {
// Type check
emp.firstName = 'Bob';
}
(emp as Person).firstName = 'Bob';
}
- 由于超類構(gòu)造函數(shù)的參數(shù)在構(gòu)造函數(shù)執(zhí)行之前執(zhí)行祠够,所以 參數(shù)可以是一個表達式或者 一個方法調(diào)用:
class Employee extends Person {
// ...
Employee() : super.fromJson(findDefaultData());
}
注意: 1. 如果在構(gòu)造函數(shù)的初始化列表中使用
super()
压汪,需要把它放到最后。 2.調(diào)用超類構(gòu)造函數(shù)的參數(shù)無法訪問this
古瓤。 例如止剖,參數(shù)可以為靜態(tài)函數(shù)但是不能是實例函數(shù)。
- 在構(gòu)造函數(shù)體執(zhí)行之前除了可以調(diào)用超類構(gòu)造函數(shù)之外落君,還可以 初始化實例參數(shù)穿香。 使用逗號分隔初始化表達式。
如Initializer list(初始化列表):
class Point {
num x;
num y;
Point(this.x, this.y);
// 構(gòu)造函數(shù)體執(zhí)行之前,初始化實例參數(shù)
Point.fromJson(Map jsonMap)
: x = jsonMap['x'],
y = jsonMap['y'] {
print('In Point.fromJson(): ($x, $y)');
}
}
警告: 初始化表達式等號右邊的部分不能訪問
this
绎速。
3.4.Redirecting constructors(重定向構(gòu)造函數(shù))
有時候一個構(gòu)造函數(shù)會調(diào)動類中的其他構(gòu)造函數(shù)皮获。 一個重定向構(gòu)造函數(shù)是沒有代碼的,在構(gòu)造函數(shù)聲明后朝氓,使用 :
(冒號)調(diào)用其他構(gòu)造函數(shù)魔市。
class Point {
num x;
num y;
// Point類的主構(gòu)造函數(shù)
Point(this.x, this.y);
// 重定向構(gòu)造函數(shù),指向主構(gòu)造函數(shù)赵哲,函數(shù)體為空
Point.alongXAxis(num x) : this(x, 0);
}
3.5.Constant constructors(常量構(gòu)造函數(shù))
如果你的類提供一個狀態(tài)不變的對象待德,你可以把這些對象 定義為編譯時常量。要實現(xiàn)這個功能枫夺,需要定義一個 const
構(gòu)造函數(shù)将宪, 并且聲明所有類的變量為 final
。
class ImmutablePoint {
final num x;
final num y;
const ImmutablePoint(this.x, this.y);
static final ImmutablePoint origin =
const ImmutablePoint(0, 0);
}
3.6.Factory constructors(工廠方法構(gòu)造函數(shù))
如果一個構(gòu)造函數(shù)并不總是返回一個新的對象橡庞,則使用 factory
來定義 這個構(gòu)造函數(shù)较坛。例如,一個工廠構(gòu)造函數(shù) 可能從緩存中獲取一個實例并返回扒最,或者 返回一個子類型的實例丑勤。
下面代碼演示工廠構(gòu)造函數(shù) 如何從緩存中返回對象。
class Logger {
final String name;
bool mute = false;
// _cache 是一個私有庫,幸好名字前有個 _ 吧趣。
static final Map<String, Logger> _cache =
<String, Logger>{};
factory Logger(String name) {
if (_cache.containsKey(name)) {
return _cache[name];
} else {
final logger = new Logger._internal(name);
_cache[name] = logger;
return logger;
}
}
Logger._internal(this.name);
void log(String msg) {
if (!mute) {
print(msg);
}
}
}
注意: 工廠構(gòu)造函數(shù)無法訪問
this
法竞。
- 使用
new
關(guān)鍵字來調(diào)用工廠構(gòu)造函數(shù)耙厚。
var logger = new Logger('UI');
logger.log('Button clicked');
四、Callable classes(可調(diào)用的類)
如果 Dart 類實現(xiàn)了 call()
函數(shù)則 可以當(dāng)做方法來調(diào)用岔霸。
在下面的示例中薛躬,WannabeFunction 類定義了一個 call()
方法,該方法有三個字符串參數(shù)呆细,并且返回三個字符串 串聯(lián)起來的結(jié)果型宝。
class WannabeFunction {
call(String a, String b, String c) => '$a $b $c!';
}
main() {
var wf = new WannabeFunction();
var out = wf("Hi","there,","gang");
print('$out');
}
關(guān)于把類當(dāng)做方法使用的更多信息,請參考 Emulating Functions in Dart(在 Dart 中模擬方法)絮爷。
五趴酣、Typedefs(別名)
在 Dart 語言中,方法也是對象略水。 使用 typedef
, 或者 function-type alias 來為方法類型命名价卤, 然后可以使用命名的方法。 當(dāng)把方法類型賦值給一個變量的時候渊涝,typedef
保留類型信息慎璧。
下面的代碼沒有使用 typedef
:
class SortedCollection {
Function compare;
SortedCollection(int f(Object a, Object b)) {
compare = f;
}
}
// 初始化,終止實現(xiàn)(不實現(xiàn)).
int sort(Object a, Object b) => 0;
main() {
SortedCollection coll = new SortedCollection(sort);
// 我們只知道 compare 是一個 Function 類型跨释,
// 但是不知道具體是何種 Function 類型胸私?
assert(coll.compare is Function);
}
當(dāng)把 f
賦值給 compare
的時候, 類型信息丟失了鳖谈。 f 的類型是 (Object
, Object
) → int
(這里 → 代表返回值類型)岁疼, 當(dāng)然該類型是一個 Function。如果我們使用顯式的名字并保留類型信息缆娃, 開發(fā)者和工具可以使用 這些信息:
typedef int Compare(Object a, Object b);
class SortedCollection {
Compare compare;
SortedCollection(this.compare);
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
main() {
SortedCollection coll = new SortedCollection(sort);
assert(coll.compare is Function);
assert(coll.compare is Compare);
}
注意: 目前捷绒,
typedefs
只能使用在 function 類型上,但是將來 可能會有變化贯要。
由于 typedefs
只是別名暖侨,他們還提供了一種 判斷任意 function 的類型的方法。例如:
typedef int Compare(int a, int b);
int sort(int a, int b) => a - b;
main() {
assert(sort is Compare); // True!
}