• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Dart语法快速上手四《Dart2之操作符、循环、条件控制、异常》 ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Dart绝大多数的操作符和其他语言很相似,先列一张表

下面说一些不常见的

  • as 强转操作符
(emp as Person).firstName = 'Bob';
  • is / is! 判断对象类型操作符
if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}else if(emp is! Person){
.....
}
  • 空赋值操作符
b ??= value; //当b为空的时候,value的值才会赋值给b
  • ?. 类似于Kotlin的非空判断,a?.b 在a不为空的时候执行a.b

  • for in循环,除了常规的for循环以外,还支持for in 循环

var collection = [0, 1, 2];
for (var x in collection) {
  print(x); // 0 1 2
}
  • Switch case 除了正常的比较也是支持枚举类型的
var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    // ERROR: Missing break

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

还有一种用法是在进入一个case之后根据判断如果true我要执行A case 如果是false我要执行 B case,Dart也提供了支持,利用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;
}

断言

Dart里面支持断言,你必须确保判断是正确的才能通过这个断言,断言在生产环境中不起作用

// Make sure the variable has a non-null value.
assert(text != null);

// Make sure the value is less than 100.
assert(number < 100);

// Make sure this is an https URL.
assert(urlString.startsWith('https'));

异常

  • throw Exception
    void distanceTo(Point other) => throw UnimplementedError();//这是抛出异常的方法

  • catch

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  // A specific exception
  buyMoreLlamas();
} on Exception catch (e) {
  // Anything else that is an exception
  print('Unknown exception: $e');
} catch (e) {
  // No specified type, handles all
  print('Something really unknown: $e');
}

on和catch的区别应该在于是否关心异常的实例

  • 捕获堆栈信息
try {
  // ···
} on Exception catch (e) {
  print('Exception details:\n $e');
} catch (e, s) {
  print('Exception details:\n $e');
  print('Stack trace:\n $s');
}

你可以在catch里面多增加一个参数,第一个是异常的实例,第二个则是错误的堆栈信息

  • rethrow
    Dart允许你在捕获异常的同时进行传播,如果你需要这样做,请使用rethrow关键字
void misbehave() {
  try {
    dynamic foo = true;
    print(foo++); // Runtime error
  } catch (e) {
    print('misbehave() partially handled ${e.runtimeType}.');
    rethrow; // Allow callers to see the exception.
  }
}

void main() {
  try {
    misbehave();
  } catch (e) {
    print('main() finished handling ${e.runtimeType}.');
  }
}

By the way .Dart does support “Finally” keyWord too.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
用Flutter + Dart快速构建一款绝美移动App发布时间:2022-07-13
下一篇:
Flutter实战(1)-------初识Dart发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap