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