2.13 后新特性

空安全

Null safety 翻译成中文的意思就是空安全,它可以帮助开发哲避免一些日常开发中很难被发现的错误,并且额外的好处是可以改善性能。

flutter 2.2.0 之后的版本都要求使用 null safety。

?可空类型

变量检查


String username="张三"; // 表示非空的String类型
username=null;         // 非空String类型赋值时会提示 A value of type 'Null' can't be assigned to a variable of type 'string' 错误

String? username="张三"; // String? 表示username是一个可空类型
username=null;          // 赋空值不会报错

方法检查

String? getData(apiUrl){
    if(apiUrl!=null){
        return "this is server data";
    }
    return null;
}

!类型断言

变量检查

String? str="this is str";
str=null;
print(str!.length); // 如果str不等于null,会打印str的长度,如果等于null会抛出异常

late 关键字

late 关键字主要用于延迟初始化。

class Person {
    late String name;
    late int age;

    void setName(String name, int age){
        this.name = name;
        this.age = age;
    }

    String getName() {
        return "${this.name}---${this.age}"
    }
}

required 关键字

最开始 @required 是注解,现在它已经作为内置修饰符,主要用于允许根据需要标记任何命名参数(函数或类),使得他们不为空,因为可选参数中必须有个 required。

class Person {
    String? name; // 可空属性
    int age;
    Person({this.name,required this.age}); // 表示 name 可以传入也可以不传入,age 必须传入
    Person({required this.name,required this.age}); // 表示 name 和 age 必须传入

    String getName() {
        return "${this.name}---${this.age}";
    }
}

void main(args) {
    Person p=new Person(
        name: "张三",
        age: 20
    );
    print(p.getName());

    Person p1=new Person(
        age: 20
    );
    print(p.getName());
}
posted @ 2025-10-18 17:15  505donkey  阅读(11)  评论(0)    收藏  举报