你能将命名参数与短手构造函数参数结合起来吗?

问题描述 投票:10回答:2

在飞镖:

命名参数的功能类似于 -

String send(msg, {rate: 'First Class'}) {
  return '${msg} was sent via ${rate}';
}

// you can use named parameters if the argument is optional
send("I'm poor", rate:'4th class'); // == "I'm poor was sent via 4th class"

简写构造函数参数的功能类似于 -

class Person {
  String name;

  // parameters prefixed by 'this.' will assign to
  // instance variables automatically
  Person(this.name);
}

有没有办法做下面的事情? -

class Person{
   String name;
   String age;

   Person({this.name = "defaultName", this.age = "defaultAge"});
}

//So that I could do something like:
var personAlpha = new Person(name: "Jordan");

谢谢,

代码样本来自dartlang synonyms

constructor dart optional-parameters named-parameters
2个回答
8
投票

你只需要使用冒号而不是等号

class Person {
   String name;
   String age;

   Person({this.name = "defaultName", this.age = "defaultAge"});
}

我发现这仍然令人困惑,可选参数使用=来指定默认值,但命名为use :。应该问自己。


2
投票

你可以使用“这个”。所有参数类型的语法。如上所述,您需要':'作为命名参数的默认值。

你甚至可以使用“这个”。对于函数类型参数:

class C {
  Function bar;
  C({int this.bar(int x) : foo});

  static foo(int x) => x + 1;
}
© www.soinside.com 2019 - 2024. All rights reserved.