Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Const constructor is not working on Dart and shows id as 0

I’m learning Dart using the Dart Apprentice book. Can you tell me why this code shows 0 as id even though I have created const object as const vicki = User(id: 24, name: 'Vicki');

Please let me know what the issue is with this code?

void main() {
  const vicki = User(id: 24, name: 'Vicki');
  print(vicki.id); // it shows 0. But it must be 24
}


class User {
 

  final int id = 0;
  final String name = '';

  const User({int id = 0, String name = "anonymous"});
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The named arguments in your current code are not setting any value in your object. You are therefore just declaring some parameters to the constructor without using any of them.

Your code should instead be written as:

void main() {
  const vicki = User(
    id: 24,
    name: 'Vicki',
  );
  print(vicki.id); // 24
}

class User {
  final int id;
  final String name;

  const User({
    this.id = 0,
    this.name = "anonymous",
  });
}

Which is a shortcut of writing the following:

class User {
  final int id;
  final String name;

  const User({
    int id = 0,
    String name = "anonymous",
  })  : this.id = id,
        this.name = name;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading