首页 > 解决方案 > 如何在飞镖中创建多个构造函数?

问题描述

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

class A{
  String b,c,d;

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

}

标签: flutterdart

解决方案


请参阅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);
}

推荐阅读