0

【笔记】Dart的空安全

 1 year ago
source link: https://loli.fj.cn/2023/03/17/Dart%E7%9A%84%E7%A9%BA%E5%AE%89%E5%85%A8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

为了防止变量数据为空导致程序报错,最新版本Dart引入了空安全,当一个不为空的变量赋值为null时将不能被编译

  • 在定义变量的数据类型时,在数据类型后加?关键字,表示该变量是一个可空类型的变量
数据类型? 变量名 = 变量值;
  • 方法的返回值也可以通过?定义为可空类型
返回值类型? 方法名() {
...
}
  • 如果一个可空类型的变量执行一些可能会导致报错的方法时,为了强制执行(可能会抛出异常),可以在变量后加!避免无法编译
  • 为了防止类型断言抛出异常,通常配合try...catch处理异常
String? str = "";
try {
str!.length;
} catch (e) {
...
}

延迟初始化

  • 如果在类中定义了属性,而没有构造方法为属性赋值,此时可能出现属性值为空的情况,导致无法编译
  • 使用late关键字修饰属性,表示延迟初始化
class 类名 {
late 数据类型 属性名;
}

命名参数允许空值

  • 如果方法的形参列表指定了命名参数,而命名参数没有指定默认值,可以使用required关键字修饰参数,允许为空值
返回值类型 方法名({required 数据类型 形参名}) {
...
}

哔哩哔哩——筱筱知晓


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK