在這一步中,你改變的僅是 Dart 的代碼,你可以自己為你新建的類(lèi)起個(gè)名字,當(dāng)創(chuàng)建這個(gè)類(lèi)的一個(gè)實(shí)例,隨機(jī)選擇一個(gè)名字和稱(chēng)謂,或者你可以提供一個(gè)名字和稱(chēng)謂給構(gòu)造函數(shù)。
在文件的頂部加入 import
import 'dart:html';
?
import 'dart:math' show Random;
piratebadge.dart
show
關(guān)鍵字,你可以只導(dǎo)入你需要的類(lèi),方法,和屬性。Random
提供了一個(gè)隨機(jī)數(shù)的發(fā)生器。 加入一個(gè)類(lèi)的聲明在在文件的底部
...
class PirateName {
}
創(chuàng)建一個(gè)類(lèi)級(jí)別的 Random 實(shí)體
class PirateName {
static final Random indexGen = new Random();
}
static
定義類(lèi)級(jí)別的字段,就是說(shuō)隨機(jī)數(shù)發(fā)生器被所有的類(lèi)實(shí)例共享。new
調(diào)用一個(gè)構(gòu)造函數(shù)。 在類(lèi)中加入兩個(gè)成員變量,一個(gè)定義 first name ,一個(gè)定義 appellation 。
class PirateName {
static final Random indexGen = new Random();
String _firstName;
String _appellation;
}
(_).
強(qiáng)調(diào)。Dart 沒(méi)有 private 關(guān)鍵字。 在類(lèi)內(nèi)創(chuàng)建兩個(gè)靜態(tài)的 List ,提供 names 和 appellations 兩個(gè)集合供選擇。
class PirateName {
...
static final List names = [
'Anne', 'Mary', 'Jack', 'Morgan', 'Roger',
'Bill', 'Ragnar', 'Ed', 'John', 'Jane' ];
static final List appellations = [
'Jackal', 'King', 'Red', 'Stalwart', 'Axe',
'Young', 'Brave', 'Eager', 'Wily', 'Zesty'];
}
final
修飾的變量不能更改。List 類(lèi)提供 API 給列表。
給類(lèi)提供一個(gè)構(gòu)造函數(shù)。
class PirateName {
...
PirateName({String firstName, String appellation}) {
if (firstName == null) {
_firstName = names[indexGen.nextInt(names.length)];
} else {
_firstName = firstName;
}
if (appellation == null) {
_appellation = appellations[indexGen.nextInt(appellations.length)];
} else {
_appellation = appellation;
}
}
}
({ })
是可選的被命名的參數(shù)。nextInt()
函數(shù)得到一個(gè)隨機(jī)整數(shù)從隨機(jī)數(shù)發(fā)生器里。([ ])
為列表添加索引。length
屬性返回列表中元素的個(gè)數(shù)。提供一個(gè) getter
給私有字段。
class PirateName {
...
String get pirateName =>
_firstName.isEmpty ? '' : '$_firstName the $_appellation';
}
?:
是 if-then-else
語(yǔ)句的簡(jiǎn)略寫(xiě)法。('$_firstName the $_appellation')
讓我們很容易從其他對(duì)象構(gòu)建字符串。( => expr; )
是 { return expr; }
語(yǔ)法的一個(gè)簡(jiǎn)稱(chēng)。 重寫(xiě) toString()
方法。
class PirateName {
...
String toString() => pirateName;
}
toString()
方法沒(méi)有給很多的信息,很多類(lèi)重寫(xiě) toString()
。 print(anObject)
得到字符串,返回值是 anObject.toString()
得到的。 toString()
在的調(diào)試和輸出的時(shí)候特別有用。 修改 setBadgeName()
方法,使用 PirateName 而不是 String 。
void setBadgeName(PirateName newName) {
querySelector('#badgeName').text = newName.pirateName;
}
更改 updateBadge()
基于輸入字段的值生成 PirateName 。
void updateBadge(Event e) {
String inputName = (e.target as InputElement).value;
?
setBadgeName(new PirateName(firstName: inputName));
...
}
更改 generateBadge()
生成一個(gè) PirateName 而不是使用 Anne Bonney
。
void generateBadge(Event e) {
setBadgeName(new PirateName());
}
使用 File > Save All
保存。
運(yùn)行應(yīng)用正確點(diǎn)擊 piratebadge.html
并選擇 Run in Dartium
。
把你的應(yīng)用和下面的比較。
在輸入框中輸入。刪除輸入字段。點(diǎn)擊按鈕。
更多建議: