【问题标题】:How can I create multiple constructors in dart?如何在飞镖中创建多个构造函数?
【发布时间】:2019-06-19 13:59:21
【问题描述】:

我想通过调用具有不同数量参数的构造函数来创建不同的对象。我怎样才能在 Dart 中实现这一点?

class A{
  String b,c,d;

  A(this.b,this.c)
  A(this.b,this.c,this.d)

}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    Constructor section of Tour of Dart

    Dart 基本上不支持方法/构造函数重载。然而 Dart 允许命名构造函数和可选参数。

    在您的情况下,您可以:

    class A{
      String b,c,d;
    
      /// with d optional
      A(this.b, this.c, [this.d]);
    
      /// named constructor with only b and c
      A.c1(this.b, this.c);
      /// named constructor with b c and d
      A.c2(this.b, this.c, this.d);
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用factory constructors

      class A{
        String b,c,d;
      
        A(this.b,this.c,this.d)
        
        factory A.fromBC(String b, String c) => A(b, c, "");
      }
      

      【讨论】:

        【解决方案3】:

        为了清楚起见,您可以使用命名构造函数来为一个类实现多个构造函数。

        class A{
              String b,c,d;
        
              // A(); //default constructor no need to write it
              A(this.b,this.c); //constructor #1
            
              A.namedConstructor(this.b,this.c,this.d); //another constructor #2
            
            }
        

        【讨论】:

        • 会有一个错误“'A' is already declared in this scope”,因为你不能有 2 个未命名的构造函数。
        • 我的意思是构造函数A();被dart初始化为默认值。不需要初始化它。谢谢...
        • 并非如此,如果提供了明确的默认值,则不再生成默认值。如果你尝试实例化 A(),将会出现错误:“位置参数太少:需要 2 个,给定 0 个。”
        猜你喜欢
        • 1970-01-01
        • 2018-10-29
        • 1970-01-01
        • 2018-10-20
        • 2020-04-03
        • 2019-08-04
        • 1970-01-01
        • 2019-01-05
        相关资源
        最近更新 更多