Параметры по умолчанию в классе

Начала изучать Dart. Остановилась на классах и уже какой день бьюсь над вопросом: как задать значения по умолчанию в конструкторе класса? Да, можно сделать несколько конструкторов с разными наборами параметров. Но, может, это возможно реализовать в одном? Как в python, например...

Последнее, до чего я добралась(конечно, это не работает ;( )

class Person{
  String name;
  int age;
  bool hasDog;
  int countDog;
  List<String> dogNames;
  
  Person(this.name, this.age, this.hasDog, [this.countDog = 0, this.dogNames = List<String>]);
}
 
void main() {
  Person ivan = Person('Иван', 35, false);
  Person mary = Person('Марья', 22, true, 2, ['Тузик', 'Бобик']);
}

Ответы (1 шт):

Автор решения: MiT

Исправил основной конструктор и добавил второй конструктор с именованными параметрами:

class Person {
  final String name;
  final int age;
  final bool hasDog;
  final int countDog;
  final List<String> dogNames;

  const Person(
    this.name,
    this.age,
    this.hasDog, [
    this.countDog = 0,
    this.dogNames = const <String>[],
  ]);

  const Person.two(
    this.name,
    this.age,
    this.hasDog, {
    this.countDog = 0,
    this.dogNames = const <String>[],
  });

  const Person.three(
    this.name,
    this.age,
    this.hasDog, {
    this.countDog = 0,
    this.dogNames = const <String>['Тузик', 'Бобик'],
  });

  Person copyWith({
    final String? name,
    final int? age,
    final bool? hasDog,
    final int? countDog,
    final List<String>? dogNames,
  }) {
    return Person(
      name ?? this.name,
      age ?? this.age,
      hasDog ?? this.hasDog,
      countDog ?? this.countDog,
      dogNames ?? this.dogNames,
    );
  }

  @override
  String toString() =>
      'name: $name, age: $age, hasDog: $hasDog, countDog: $countDog, dogNames: $dogNames';
}

void main() {
  Person ivan = Person('Иван', 35, false);
  Person mary = Person('Марья', 22, true, 2, ['Тузик', 'Бобик']);
  Person andrey = Person.two('Андрей', 16, false);
  Person paha =
      Person.two('Паша', 16, false, countDog: 2, dogNames: ['Тузик', 'Бобик']);

  mary = mary.copyWith(dogNames: [...mary.dogNames, "Рекс"]);

  print(ivan);
  print(mary);
  print(andrey);
  print(paha);
}
→ Ссылка