Search code examples
constructordartoptional-parametersnamed-parameters

Can you combine named parameter with short-hand constructor parameter?


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


Solution

  • 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.