You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
2.1 KiB
Dart

void basic_variables() {
print("\nDart Variables:");
var name = "Bobson";
// name = 123;
// Error: A value of type 'int' can't be assigned to a variable of type 'String'.
print(name);
dynamic myName = "Bobson";
print(myName);
myName = 123;
print(myName);
// var list = [
// 1,
// "2",
// 3.0,
// true,
// () {},
// #symbol,
// Runes("123"),
// [1, 2, 3],
// {"A": 4}
// ];
int lineCount;
assert(lineCount == null); // default value is null
}
void basic_control_flow() {
print("\nDart Control Flow:");
int number = -5;
// If Else
if (number > 0) {
print("$number 大於 0");
} else if (number < 0) {
print("$number 小於 0");
} else {
print("$number 等於 0");
}
// Switch
switch (number > 0) {
case true:
print("$number 大於 0");
break;
default:
print("$number 小於等於 0");
}
DownloadState downloadState = DownloadState.done;
switch (downloadState) {
case DownloadState.none:
print("尚未下載");
break;
case DownloadState.downloading:
print("下載中");
break;
case DownloadState.done:
print("下載完成");
break;
case DownloadState.error:
print("下載失敗");
break;
default:
throw Exception("異常狀態");
}
// For loop
var collection = [];
for (var i = 0; i < 3; i++) {
collection.add(i);
}
print(collection);
collection.forEach((i) => print("${i+1}"));
print(collection.map((i) => i+1));
for (var c in collection) {
print(c);
}
// While
int count = 0;
while (count < 5) {
count += 1;
}
print(count);
do {
count += 5;
print("count 加一次 5");
} while (count < 14);
print(count);
// Break Continue
count = 0;
while (count < 5) {
if (count == 4) {
count += 3;
continue;
}
// continue 會忽略這行,直接進入下一個迴圈
count += 1;
}
print(count);
do {
count += 5;
print("count 加一次 5");
if (count % 2 == 0) break;
} while (count < 14);
print(count);
}
enum DownloadState {
none,
downloading,
done,
error
}