【问题标题】:How can I get a default and a parameterized constructor inside the same class in Dart/Flutter?如何在 Dart/Flutter 的同一个类中获取默认构造函数和参数化构造函数?
【发布时间】:2020-10-06 00:27:51
【问题描述】:

我知道在 C++ 中我们可以毫无问题地拥有这两个构造函数。在 Dart 中,当我尝试编写两个构造函数时,它说“默认构造函数已定义”

class Human {
  double height;
  int age;

  Human()
  {
    height = 0;
      age = 0;
  }

  Human (double startingheight){        //The default constructor is already defined
    height = startingheight;
  }

}

【问题讨论】:

标签: flutter dart


【解决方案1】:

试试这些

//Using Default parameter values
Human({this.height = 0.0, this.age = 0});

// Named constructor
Human.startingHeight(double startingHeight){ 
    height = startingHeight;
    age = 0;//or don't use this if you want it null
}

欲了解更多信息,请查看此页面:https://dart.dev/guides/language/language-tour

【讨论】:

    【解决方案2】:

    Dart 在任何可见的未来都不支持方法/函数重载和will not have it

    你可以在这里做的是将参数optional设为默认值:

    作为位置参数:

    class Human {
      double height = 175;
      Human([this.height]);
    }
    
    var human1 = Human(); 
    var human = Human(180);
    

    或命名:

    class Human {
      final double height;
      Human({this.height = 175});
    }
    
    var human1 = Human(); 
    var human = Human(height: 180);
    

    【讨论】:

      【解决方案3】:
      class Human{
            Human(double height, int color) {
            this._height = height;
            this._color = color;
         }
      
         Human.fromHuman(Human another) {
            this._height = another.getHeight();
            this._color = another.getColor();
         }  
      }
      
      new Human.fromHuman(man);
      

      这个构造函数可以简化

      Human(double height, int age) {
         this._height = height;
         this._age = age;
      }
      

      Human(this._height, this._age);
      

      命名构造函数也可以是私有的,名称以_开头

      具有final 字段初始值设定项列表的构造函数是必需的:

      class Human{
        final double height;
        final int age;
      
        Human(this.height, this.age);
      
        Human.fromHuman(Human another) :
          height= another.height,
          age= another.age;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-03
        • 2017-05-19
        • 1970-01-01
        • 2016-03-24
        • 2013-03-05
        • 2021-08-31
        • 2012-06-30
        • 1970-01-01
        相关资源
        最近更新 更多