'What is the use of constant values in dart?
As described in the documentations:
The const keyword isn’t just for declaring constant variables. You can also use it to create constant values, as well as to declare constructors that create constant values. Any variable can have a constant value.
Can someone explain the use of constant values?
Solution 1:[1]
I want to add, that another point for const
is to guarantee your get the same instance of the object each time you construct it with the same parameters:
class Test {
final int value;
const Test(this.value);
}
void main() {
print(Test(5).hashCode == Test(5).hashCode); // false
print((const Test(5)).hashCode == (const Test(5)).hashCode); // true
}
This is the reason why the const
constructor can be difficult to make for all objects since your need to make sure the object can be constructed on compile-time. Also, why after creation of the object no internal state can be changed as the previous answer also shows.
Solution 2:[2]
This is a simple example which I hope explains clearly:
Start with two variables and a constant.
var foo = [10,11];
var bar = const [20,21];
const baz = [30,31];
Try to modify foo
and it succeeds.
foo.add(12); // [10,11,12]
Try to similarly modify bar
and there's an error, because even though bar
is a variable, its value was declared to be a constant, thus is immutable.
bar.add(22); // ERROR!
Try to reassign bar
to a different value. That works since bar
itself was not declared as a constant.
bar = [40,41];
Now, try to modify bar
's value again and this time it works, since its new value is not a constant.
bar.add(42) // [40,41,42]
Try to modify baz
and there's an error, since baz
being declared as a constant itself, its value is inherently immutable.
baz.add(32); // ERROR!
Try reassigning baz
to a new value and it fails because baz
is a constant and can't be reassigned to a new value.
baz = [50,51]; // ERROR!
Solution 3:[3]
void main() {
simpleUse();
finalUse();
constUse();
}
simpleUse() {
print("\nsimple declaration");
var x = [10];
print('before: $x');
x = [5];//changing reference allowed
x.add(10);//changing content allowed
print('after: $x');
}
finalUse() {
print("\nfinal declaration");
final x = [10];
print('before: $x');
// x = [10,20]; //nope changing reference is not allowed for final declaration
x.add(20); //changing content is allowed
print('after: $x');
}
constUse() {
print("\nconst declaration");
const x = [10];
print('before: $x');
// x = [10,20]; //nope -> changing reference is not allowed for final declaration
// x.add(20);//nope -> changing content is not allowed
print('after: $x');
}
Also, variables are simple values like x = 10;
values are instances of enums, list, maps, classes, etc.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | julemand101 |
Solution 2 | Michael Ekoka |
Solution 3 | Doc |