flutter语言篇三

187 阅读1分钟

特殊操作符

1. as,is,is!

as 类型转换

(emp as Person).firstName = 'Bob';

is 类型判断

if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}

2. 赋值操作符 ??=

b值为null,则赋值为value

// Assign value to b if b is null; otherwise, b stays the same
b ??= value;

3. 条件运算符

condition为true,则值为expr1;否则为expr2

condition ? expr1 : expr2

var visibility = isPublic ? 'public' : 'private';

expr1不为空,则值为expr1;否则为expr2

expr1 ?? expr2

String playerName(String name) => name ?? 'Guest';

4. switch-case

case 后有操作语句,而无break报错

var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    // ERROR: Missing break

  case 'CLOSED':
    executeClosed();
    break;
}

case后无操作语句,可缺少break

var command = 'CLOSED';
switch (command) {
  case 'CLOSED': // Empty case falls through.
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

case后有操作语句,希望继承执行,可使用continue

var command = 'CLOSED';
switch (command) {
  case 'CLOSED':
    executeClosed();
    continue nowClosed;
  // Continues executing at the nowClosed label.

  nowClosed:
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}