Open3
Dartのconstructorについて
シンプルなコンストラクタ
class Customer {
String name;
int age;
Customer(this.name, this.age);
}
Customer customer = Customer("Taro", 23);
複数のコンスタクタをもたせる
複数のコンストラクタをもたせる場合は、Default constructorに加えてNamed constructorを使います。
class Customer {
late final String name;
late final int age;
// Default constructors
Customer(this.name, this.age);
// Named constructors
// {}(ブレース)で書くこともできる
Customer.onlyAge(this.age) {
name = "";
}
// こちらもNamed constructors
// :(コロン)で書くこともできる
Customer.onlyName(this.name)
: age = 0;
}
Customer customer1 = Customer("Taro", 23);
Customer customer2 = Customer.onlyAge(23);
Customer customer3 = Customer.onlyName("Taro");
Redirecting constructors
あるコンストラクタから、別のコンストラクタを呼び出すことができます。
class Customer {
String name;
int age;
Customer(this.name, this.age);
Customer.onlyName(String name) : this(name, 10);
}