Search code examples
dartdart-null-safety

Constructor Null safety in Dart


Tell me please. Why is pr2 null and not str1 by default?

void main() {
  var house = Home(pr1: 4, pr3: 5);
  house.printDate();
}

class Home {
  int pr1=1;
  String? pr2 = 'str1';
  int pr3=3;
  Home({required this.pr1, this.pr2, required this.pr3});

  void printDate() {
    print('The pr1: $pr1');
    print('The pr2: $pr2');
    print('The pr3: $pr3');
  }
}

The pr1: 4 The pr2: null The pr3: 5


Solution

  • Because optional parameters are by default null unless otherwise specified in the constructor definition. If you want to declare another default value, you need to use this syntax:

    void main() {
      var house = Home(pr1: 4, pr3: 5);
      house.printDate();
      // The pr1: 4
      // The pr2: str1
      // The pr3: 5
    }
    
    class Home {
      int pr1=1;
      String? pr2;
      int pr3=3;
      Home({required this.pr1, this.pr2 = 'str1', required this.pr3});
    
      void printDate() {
        print('The pr1: $pr1');
        print('The pr2: $pr2');
        print('The pr3: $pr3');
      }
    }