Dart Multiple Constructors

后端 未结 7 1689
一向
一向 2021-02-03 16:51

Is it really not possible to create multiple constructors for a class in dart?

in my Player Class, If I have this constructor

Player(String name, int col         


        
7条回答
  •  你的背包
    2021-02-03 17:12

    How about the case you want to have more than one constructor. For example, there are 2 constructors you desire to use:

    Customer(String name, int age, String location) {
      this.name = name;
      this.age = age;
      this.location = location;
    }
    
    Customer(this.name, this.age) {
      this.name = name;
      this.age = age;
    }
    

    But if you define both of them in a class, there will be a compiler error.

    Dart provides Named constructor that helps you implement multiple constructors with more clarity:

    class Customer {
      // ...
    
      Customer(String name, int age, String location) {
        this.name = name;
        this.age = age;
        this.location = location;
      }
    
      // Named constructor - for multiple constructors
      Customer.withoutLocation(this.name, this.age) {
        this.name = name;
        this.age = age;
      }
    
      Customer.empty() {
        name = "";
        age = 0;
        location = "";
      }
    
      @override
      String toString() {
        return "Customer [name=${this.name},age=${this.age},location=${this.location}]";
      }
    }
    

    You can write it more simply with Syntactic sugar:

    Customer(this.name, this.age, this.location);
    
    Customer.withoutLocation(this.name, this.age);
    
    Customer.empty() {
      name = "";
      age = 0;
      location = "";
    }
    

    Now we can create new Customer object by these methods.

    var customer = Customer("bezkoder", 26, "US");
    print(customer);
    // Customer [name=bezkoder,age=26,location=US]
    
    var customer1 = Customer.withoutLocation("zkoder", 26);
    print(customer1);
    // Customer [name=zkoder,age=26,location=null]
    
    var customer2 = Customer.empty();
    print(customer2);
    // Customer [name=,age=0,location=]
    

    So, is there any way to make Customer.empty() neat? And how to initialize an empty value for location field when calling Customer.withoutLocation() instead of null?

    From : Multiple Constructors

提交回复
热议问题