Flutter 学习从零开始-Dart流程控制语句

2020-07-28  本文已影响0人  風清雲少

if-else 条件语句

String playName(String name) {
  if (name != null) {
    return name;
  } else {
    return "Guest";
  }
}

String playName2(String name) {
  return name != null ? name : "Guest";
}

String playName3(String name) {
  return name ?? "Guest";
}

for 循环语句

 for (int i = 0; i < arr.length; i++) {
    print(arr[i]);
  }
 for (var item in arr) {
   print(item);
 }
 arr.forEach((element) {
   print(element);
 });

while do-while 语句

int x =10;
while(x > 0){
  print (x--);
}

int y = 10;
do{
  print(y--);
}while(y>0);

witch 语句

String s="A";
switch(s){
case 'A':
  print('优秀');
break;
case 'B':
  print('良好');
break;
default:
  print("未知");
break;
}

break 跳出循环, continue 结束本次循环,开始下一轮循环

assert 语句

异常

throw FormatException('Expected a least 1 section');
throw 'Out of llamas!';

高质量代码建议异常类型为 Exception 和Error,以及一些子类型。

try{
   breedMoreLlamas();
} on OutOfLamasException{
   buyMoreLlamas();
}
try{
  breadMoreLlamas();
} on OutOfLlamasException{
  buyMoreLlamas();
} on Exception catch(e){
  print('Unknown exception: $e');
} catch( e,s){
  print('Something really unknown; $e');
  print('Stack trace:\n $s');
}
try{
  breedMoreLlamas();
} finally{
  cleanLlamaStalls();
}
上一篇下一篇

猜你喜欢

热点阅读