Dart Multiple Constructors

后端 未结 7 1665
一向
一向 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:15

    You can only have one unnamed constructor, but you can have any number of additional named constructors

    class Player {
      Player(String name, int color) {
        this._color = color;
        this._name = name;
      }
    
      Player.fromPlayer(Player another) {
        this._color = another.getColor();
        this._name = another.getName();
      }  
    }
    
    new Player.fromPlayer(playerOne);
    

    This constructor can be simplified

      Player(String name, int color) {
        this._color = color;
        this._name = name;
      }
    

    to

      Player(this._name, this._color);
    

    Named constructors can also be private by starting the name with _

    class Player {
      Player._(this._name, this._color);
    
      Player._foo();
    }
    

    Constructors with final fields initializer list are necessary:

    class Player {
      final String name;
      final String color;
    
      Player(this.name, this.color);
    
      Player.fromPlayer(Player another) :
        color = another.color,
        name = another.name;
    }
    

提交回复
热议问题