Reputation: 51
I have a class with an immutable property, int id. How do I pass the value of id to the constructor?
class Hey
{
var val;
final int id;
Hey(int id,var val)
{
this.id=id;
this.val=val;
}
}
void main()
{
Hey hey=new Hey(0,1);
}
hey.dart:10:10: Error: Setter not found: 'id'. this.id=id; ^^ hey.dart:10:10: Error: The setter 'id' isn't defined for the class 'Hey'. - 'Hey' is from 'hey.dart'. Try correcting the name to the name of an existing setter, or defining a setter or field named 'id'. this.id=id; ^^
I don't think a setter is required for a const or final field property. The API is not clear on how to handle this.
Upvotes: 5
Views: 1818
Reputation: 90155
From the Dart language tour:
Note: Instance variables can be
final
but notconst
. Final instance variables must be initialized before the constructor body starts — at the variable declaration, by a constructor parameter, or in the constructor’s initializer list.
And the section on initializer lists says:
Besides invoking a superclass constructor, you can also initialize instance variables before the constructor body runs. Separate initializers with commas.
// Initializer list sets instance variables before // the constructor body runs. Point.fromJson(Map<String, num> json) : x = json['x'], y = json['y'] { print('In Point.fromJson(): ($x, $y)'); }
So the general way is through initialization lists.
As mentioned above, you also can initialize at variable declaration:
class Foo {
final x = 42;
}
or can initialize them by a constructor parameter:
class Foo {
final x;
Foo(this.x);
}
although those other approaches might not always be applicable.
Upvotes: 4