Open3

Dartのconstructorについて

Shun UematsuShun Uematsu

シンプルなコンストラクタ

class Customer {
  String name;
  int age;

  Customer(this.name, this.age);
}
Customer customer = Customer("Taro", 23);
Shun UematsuShun Uematsu

複数のコンスタクタをもたせる

複数のコンストラクタをもたせる場合は、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");
Shun UematsuShun Uematsu

Redirecting constructors

あるコンストラクタから、別のコンストラクタを呼び出すことができます。

class Customer {
  String name;
  int age;
  
  Customer(this.name, this.age);
  
  Customer.onlyName(String name) : this(name, 10);
}