Loops循环
- for loops
- while and do while loops
- break and continue
- Branching, like if and switch
- Exceptions, like try, catch, and throw
for、for-in、forEach
var callbacks = [];
for (var i = 0; i < 2; i++) {
callbacks.add(() => print(i));
}
// The output is 0 and then 1
for (final c in callbacks) {
c();
}
// 使用pattern
for (final Candidate(:name, :yearsExperience) in candidates) {
print('$name has $yearsExperience of experience.');
}
// forEach
var collection = [1, 2, 3];
collection.forEach(print); // 1 2 3
while and do while
while (!isDone()) {
doSomething();
}
do {
printLine();
} while (!atEndOfPage());
Break and continue
while (true) {
if (shutDownRequested()) break;
processIncomingRequests();
}
for (int i = 0; i < candidates.length; i++) {
var candidate = candidates[i];
if (candidate.yearsExperience < 5) {
continue;
}
candidate.interview();
}
// If you're using an Iterable such as a list or set, how you write the previous example might differ:
candidates
.where((c) => c.yearsExperience >= 5)
.forEach((c) => c.interview());
Branches 分支
- if statements and elements
- if-case statements and elements
- switch statements and expressions
- Loops, like for and while
- Exceptions, like try, catch, and throw
if、if-case
if (isRaining()) {
you.bringRainCoat();
} else if (isSnowing()) {
you.wearJacket();
} else {
car.putTopDown();
}
if (pair case [int x, int y]) {
print('Was coordinate array $x,$y');
} else {
throw FormatException('Invalid coordinates.');
}
Switch
switch语句
var command = 'OPEN';
switch (command) {
case 'CLOSED':
executeClosed();
case 'PENDING':
executePending();
case 'APPROVED':
executeApproved();
case 'DENIED':
executeDenied();
case 'OPEN':
executeOpen();
default:
executeUnknown();
}
switch (command) {
case 'OPEN':
executeOpen();
continue newCase; // Continues executing at the newCase label.
case 'DENIED': // Empty case falls through.
case 'CLOSED':
executeClosed(); // Runs for both DENIED and CLOSED,
newCase:
case 'PENDING':
executeNowClosed(); // Runs for both OPEN and PENDING.
}
switch 表达式
var x = switch (y) { ... };
print(switch (x) { ... });
return switch (x) { ... };
如何将switch语句转为表达式
// switch语句
// Where slash, star, comma, semicolon, etc., are constant variables...
switch (charCode) {
case slash || star || plus || minus: // Logical-or pattern
token = operator(charCode);
case comma || semicolon: // Logical-or pattern
token = punctuation(charCode);
case >= digit0 && <= digit9: // Relational and logical-and patterns
token = number();
default:
throw FormatException('Invalid');
}
// switch表达式
token = switch (charCode) {
slash || star || plus || minus => operator(charCode),
comma || semicolon => punctuation(charCode),
>= digit0 && <= digit9 => number(),
_ => throw FormatException('Invalid')
};
Exhaustiveness checking(穷尽检查)
穷尽检查是一种在编程中用于确保所有可能情况都被处理的技术。在 Dart 中,通常用于处理枚举类型或联合类型。
// Non-exhaustive switch on bool?, missing case to match null possibility:
switch (nullableBool) {
case true:
print('yes');
case false:
print('no');
}
例如,在处理枚举类型时,可以使用switch语句来进行穷尽检查。确保在switch语句中处理了枚举的所有可能值,否则会产生编译错误或运行时异常。如果没有处理完所有的枚举值,Dart 编译器会给出相应的错误提示,强制要求进行完整的处理,从而实现穷尽检查。
enum Day { monday, tuesday, wednesday, thursday, friday, saturday, sunday }
void handleDay(Day day) {
switch (day) {
case Day.monday:
// 处理周一的逻辑
break;
case Day.tuesday:
// 处理周二的逻辑
break;
case Day.wednesday:
// 处理周三的逻辑
break;
case Day.thursday:
// 处理周四的逻辑
break;
case Day.friday:
// 处理周五的逻辑
break;
case Day.saturday:
// 处理周六的逻辑
break;
case Day.sunday:
// 处理周日的逻辑
break;
}
}
sealed class Shape {}
class Square implements Shape {
final double length;
Square(this.length);
}
class Circle implements Shape {
final double radius;
Circle(this.radius);
}
double calculateArea(Shape shape) => switch (shape) {
Square(length: var l) => l * l,
Circle(radius: var r) => math.pi * r * r
};
Guard clause
在 Dart 中,Guard clause(卫语句)指的是在函数开头用来判断一些明显非法情况并立即退出的语句。例如常见的指针判空操作,函数参数的校验等。它的主要作用是增强代码的健壮性,减少嵌套的条件表达式,使代码更易于理解和维护。
当guard子句的计算结果为false时,执行将继续执行下一个case,而不是退出整个switch。
// Switch statement:
switch (something) {
case somePattern when some || boolean || expression:
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Guard clause.
body;
}
// Switch expression:
var value = switch (something) {
somePattern when some || boolean || expression => body,
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Guard clause.
}
// If-case statement:
if (something case somePattern when some || boolean || expression) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Guard clause.
body;
}
标签:case,控制流,while,Dart,break,switch,005,var,Day
From: https://www.cnblogs.com/ayubene/p/18224123