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.
A const constructor is an optimization! The compiler makes the object immutable, allocating the same portion of memory for all Text('Hi!') objects. But not Text(Math. random()) though, as its value can't be determined at compile time!
Dart/Flutter Constructor default value For the constructors with either Named or Positional parameters, we can use = to define default values. The default values must be compile-time constants. If we don't provide value, the default value is null.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With