Home > Software engineering >  Can required parameters in a Dart constructor be named?
Can required parameters in a Dart constructor be named?

Time:05-14

I am working with some Dart code for a Flutter/Dart class I'm taking. I expected the following code to compile, but it did not:

class Person {
  String? name;
  int? age;

  Person(this.name, this.age);

  @override
  String toString() {
    return "name: $name\nage: $age";
  }
}

void main() {
  final person = Person(name: 'Joe', age: 30);
  print(person);
}

When I made the constructor parameters optional, as below, it does compile:

class Person {
  String? name;
  int? age;

  Person({this.name, this.age});

  @override
  String toString() {
    return "name: $name\nage: $age";
  }
}

void main() {
  final person = Person(name: 'Joe', age: 30);
  print(person);
}

I tried searching the Flutter dev docs for a reason why this is so, or a way to have required parameters with their names in a constructor, but I didn't find anything. I can certainly imagine cases where I would want required constructor parameters to have names.

My pubspec.yaml specifies the following: environment: sdk: ">=2.12.0 <3.0.0"

CodePudding user response:

Your first example uses what are called "positional parameters" in dart. You cannot call a positional parameter with a name label, which is why the first example does not compile.

The second example uses "named parameters". Any parameter defined within {} is considered a named parameter and must be called using a name label. As explained in the dart language tour, named parameters are optional unless they’re explicitly marked as required.

So simply add the required keyword before any named parameter you want to require.

class Person {
  String? name;
  int? age;

  Person({required this.name, required this.age});

  @override
  String toString() {
    return "name: $name\nage: $age";
  }
}

void main() {
  final person = Person(name: 'Joe', age: 30);
  print(person);
}
  • Related