Dart Null safety 以及可空类型 非空断言

Null safety翻译成中文的意思是空安全。

null safety 可以帮助开发者避免一些日常开发中很难被发现的错误,并且额外的好处是可以改善性能。

Flutter2.2.0(2021年5月19日发布) 之后的版本都要求使用null safety。

? 可空类型

! 类型断言

定义一个可空方法

String? getData(apiUrl) {

  if (apiUrl != null) {

    return "this is server data";

  }

  return null;

}

类型断言方法

普通写法

void printLength(String? str) {

  // print(str!.length);

  if (str != null) {

   print(str.length);

  }

}

类型断言写法

void printLength(String? str) {

    try {

      print(str!.length);

    } catch(e) {

      print("str is null");

    }

}

示例 

void main(args) {

  int a = 123; // 非空的int类型

  a = null; // A value of type 'Null' can't be assigned to a variable of type 'int'.



  String name = '张三';

  name = null; // A value of type 'Null' can't be assigned to a variable of type 'String'.

}

?可空类型

void main(args) {

  // 设置可空类型 null

  String? name = '张三'; // name是一个可空类型

  name = null;

  print(name); // null



  List<String>? l1 = ['张三', '李四', '王五'];

  l1 = null;

  print(l1); // null



  // 调用可空方法

  print(getData('http://www.itying.com')); // this is server data

  print(getData(null)); // null

}

!类型断言

void main(args) {

  String? str = "this is str";

  str = null;

  print(str!.length); // 类型断言: 如果str不等于null 会打印str的长度 如果str等于null会抛出异常



  // 调用类型断言方法

  printLength(null);

  printLength("str"); // 3

  printLength(null); // str is null

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想散在风中

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值