Flutter - Dart 基础(关于类的重定向构造函数、常量构造函数、工厂构造函数、类方法)

884 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第16天,点击查看活动详情

重定向构造函数

有时候,一个构造方法需要调用另外一个构造方法,这个时候可以使用重定向构造方法。在冒号后面用 this 调用

class Student {

    String? name;
    int? age;
    double? height;

    Student.withAge(this.name, this.age);
    
    // 重定向构造函数
    Student(String name) : this.withAge(name, 12);

}

常量构造函数

有时候,传入相同的值时,希望可以返回一个对象,这个时候,可以使用常量构造函数

  • 在默认构造函数前使用关键字 const 修饰,如果参数相同,那么创建出来的对象是相同的

    void main(List<String> args) {
        var stu1 = const Student();
        var stu2 = const Student();
        
        print(identical(stu1, stu2));  //true
    }
    
    class Student {
        const Student();
    }
    
  • 在常量构造函数中,所有的成员变量必须用关键字 final 修饰

    void main(List<String> args) {
        var stu1 = const Student("dart");
        var stu2 = const Student("dart");
       
        print(identical(stu1, stu2));  //true
    }
    
    class Student {
        final String name;
        const Student(this.name);
    }
    
  • 如果将结果赋值给 const 修饰的标识符,那么 const 可以省略

    void main(List<String> args) {
        const stu1 = Student("dart");
        const stu2 = Student("dart");
        
        print(identical(stu1, stu2));  //true
    }
    
    class Student {
        final String name;
        const Student(this.name);
    }
    

工厂构造函数

在 Dart 中,可以使用关键字 factory 创建工厂构造函数

工厂构造函数和普通构造函数的区别

  • 普通构造函数会默认返回创建出来的对象
  • 工厂构造函数可以返回自己手动创建的对象
void main(List<String> args) {
    var stu1 = Student("dart");
    var stu2 = Student("dart");
    var stu3 = Student.fromJson({"name": "dart"});
    
    // 使用 Student() 工厂构造函数 和 Student.fromJson({}) 工厂构造函数创建出来的对象是同一个对象
    print(identical(stu1, stu2));  // true
    print(identical(stu2, stu3));  // true
}



class Student {
    final String name;
    static final _cache = <String, Student>{};
    
    // 工厂构造函数
    factory Student(String name) {
        return _cache.putIfAbsent(name, () => Student._internal(name));
    }
    
    // 工厂构造函数
    factory Student.fromJson(Map<String, Object> json) {
        return Student(json['name'].toString());
    }
    
    Student._internal(this.name);
}

类方法

在 Dart 中,使用关键字 static 定义类方法

class Student {
    static run() {
        print("run");
    }
}

void main(List<String> args) {
    Student.run();
}