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

Time:07-01

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"});
}

CodePudding user response:

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;
}

CodePudding user response:

Well you have to refer to the class property by using the this keyword:

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


class User {


  final int id;
  final String name;

  const User({this.id = 0, this.name = "anonymous"});
}
  •  Tags:  
  • dart
  • Related