目录
Null safety翻译成中文的意思是空安全
null safety 可以帮助开发者避免一些日常开发中很难被发现的错误,并且额外的好处是可以改善性能后的版本都要求使用nul1 safety。Flutter2.2.0(2021年5月19日发布)
?可空类型
!类型断言
main() {
//非空的int类型 A value of type 'Null' can't be assigned to a variable of type 'int'.
int? a = 123;
a = null;
String? name = "张三"; // ?表示可空类型
name = null;
List? list = ["张三", "李四", "王五"];
list.add("1");
list.add(null);
print(list);
print(getData(null));
String? str = "我是张三";
str = null;
print(str?.length);
print(str!.length); //类型断言 如果str不等于空,会打印str长度;否则,会抛出异常。
}
// 方法定义可空类型?
String? getData(str) {
if (str != null) {
return "不是空的";
}
return null;
}
// 类型断言
getData1(String? str) {
try {
print(str!.length);
} catch (e) {
print(e);
}
}
late 关键字
应该修改为下面
class Person{
late String name; //Non-nullable instance field 'name' must be initialized.
late int age;
setPerson(String name, int age){
this.name = name;
this.age = age;
}
}
required关键词:
最开始@required是注解
现在它已经作为内置修饰符。
主要用于允许根据需要标记任何命名参数(函数或类),使得它们不为空。因为可选参数中必须有个 require
main(){
printInfo1("张三", age: 11, sex: "男士");
}
printInfo1(String name, {required int age, required String sex}) {
//匿名参数 行参
print("$name----$sex---- $age");
}
printInfo2(String name, {int age = 10, String sex = "男生"}) {
//匿名参数 行参
print("$name----$sex---- $age");
}
常用的Model对象使用required
class Person1 {
String name;
int age;
Person1({required this.name,required this.age}); //表示 name、age必须传入的匿名参数
setPerson(String name, int age) {
this.name = name;
this.age = age;
}
}
或者
class Person2 {
String? name; //可空属性
int age;
Person2({this.name,required this.age}); //表示 age必须传入的匿名参数
setPerson(String name, int age) {
this.name = name;
this.age = age;
}
}