skip to Main Content

What is difference when you use curly brackets inside constructor in dart classes and when you don’t use it. And why you can not have not nullable and not initialized fields inside constructor when you use curly brackets, but you can when you don’t use curly brackets.

Here is example:

class Animal{
  String name;
  int age;

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

When I write class like this, there is error which says: "The parameter ‘name’ can’t have a value of ‘null’ because of its type, but the implicit default value is ‘null’.", and same for ‘age’.

class Animal{
  String name;
  int age;

  Animal(this.name, this.age);
}

But when I don’t use curly brackets there is no error, it allows to have null fields in constructor.

3

Answers


  1. In Dart, braces {} define named parameters, while their omission defines positional parameters. By default, when named parameters are used with curly braces, they are nullable and optional. To enforce non-nullability, use the required keyword before the parameter name. For positional parameters, they are required by default, but can still be nullable if not explicitly initialized.

    Login or Signup to reply.
  2. with braces

     void main() {
      print(Animal(name: "Stark")) ; // I dont have to enter age because 
      //  its nullable
      // it is the same as 
       print(Animal(name: "Stark" , age: null))  ; // after using braces inputs not are mapped
        print(Animal(age: null)) ; // error   name: is required
      
    }
    
      class Animal{
      String name; // not nullable
      int? age;  //  nulabble
    
      Animal({required this.name, this.age}); // 
    } 
    

    so you cant map not nullable value to null because Class Null is not a subtype of String or int or any other class after null safety

    Login or Signup to reply.
  3. When you use braces, you define named parameters. For example:

    class Animal{
      String name;
      int age;
    
      Animal({this.name, this.age});
    }
    

    You should instanciate like this:

    Animal(
      name: "Dog",
      age: 5,
    );
    

    If you define your constructor without braces, you defined positionnal parameters.

    class Animal{
      String name;
      int age;
    
      Animal(this.name, this.age);
    }
    

    Then you should instantiate like this:

    Animal("Cat", 3);
    

    If you add required keyword, you make the parameter mandatory.

    If you declare a property nullable with a ? after type, for ewample

    int? age
    

    your name parameter become not mandatory.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search