Dart: Hello World 002

Tags:

XDD

J 本書的 基本教學速度帶過 Dart XDDD

Area calculator

``````void main() {
double result = caculateArea(12, 5);
print('12 * 5 是: \$result'); // 60
}

double caculateArea(double width, double height) {
double area = width * height;
return area;
}
``````

For loops and strings

``````void main() {
String myString = 'Throw your Dart';
String result = reverse(myString);
}

String reverse(String old) {
int length = old.length;
String resString = '';
for (int i = length-1; i>=0 ; i-- ){
resString += old.substring(i, i+1);
}
return resString;
}
``````
• using position of the character
``````void main() {
String myString = 'Throw your Dart';
String result = reverse2(myString);
}

String reverse2(String old) {
int length = old.length;
String resString = '';
for (int i = length-1; i>=0 ; i-- ){
resString += old[i]
}
return resString;
}
``````
• `String result = myString.split('').reversed.join();`

Arrow syntax and the ternary operator

``````bool convertToBoolLong(int value){
if (value == 1) {
return false;
} else {
return true;
}
}

bool converToBoolLongArrow(int value) => (value == 1) ? false: true;
``````

While loops, lists, and generics

• List
• (書的寫法已經 `Deprecated` 了!)
• `var songs = List<String>();` –> GG!
``````void main() {
String mySongList = sing();
print(mySongList); // We will Rock You, Miss Murder, Hate me,

}

String sing() {
var songs = [];
var songName = '';
int i = 0;
while(i<songs.length){
songName += '\${songs[i]}, ';
i++;
}
return songName;
}
``````

forEach, map, where

• foreEach
``````void main() {
String mySongList = singForEach();
print(mySongList); // We will Rock You * Miss Murder * Hate me *
}
String singForEach() {
var songs = [];
var songName = '';
songs.forEach((s) => songName += s + " * ");
return songName;
}
``````
• map
``````void main() {
List mySongList = singMapUpper();
print(mySongList);
} // [WE WILL ROCK YOU, MISS MURDER, HATE ME]

List singMapUpper() {
var songs = [];
var upperSongs = songs.map((s) => s.toUpperCase()).toList();
return upperSongs;
}
``````
• where
``````void main() {
String mySongListWithW = singWhere();
print(mySongListWithW);
} // (We will Rock You)

String singWhere() {
var songs = [];