Pregunta

In dart:

Named parameters function like so-

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"

Short-hand constructor parameters function like so-

class Person {
  String name;

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



Is there any way to do something like the below?-

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");

Thanks,

Code samples borrowed from dartlang synonyms

¿Fue útil?

Solución

Update

Yes, the = is allowed in Dart 2 and is now preferred over the : to match optional positional parameters.

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

Old Answer

You just have to use a colon instead of equals

class Person {
   String name;
   String age;

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

I find this still confusing that optional parameters use = to assign defaults but named use :. Should ask myself.

Otros consejos

You can use the "this." syntax with all argument types. As answered above, you need ':' for default values for named parameters.

You can even use "this." for function typed parameters:

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

  static foo(int x) => x + 1;
}

You can also add an required field to skip the default initialization, like so:

class ProcessArguments {
  final String logoImagePath;
  final String textLogoImagePath;

  ProcessArguments({required this.logoImagePath, required this.textLogoImagePath});
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top