In Dart, both const
and final
are used to declare variables that can’t be reassigned after they’re initialized. However, there are some differences between them:
- Use
const
to declare a compile-time constant. The value of aconst
variable must be known at compile time. When you create an object usingconst
, Dart ensures that there is only one instance of that object.const
can be used to create constant values of built-in types, as well as classes and collections that are alsoconst
. - Use
final
to declare a variable that can only be set once. It doesn’t have to be initialized at compile-time, but once it’s initialized, it can’t be changed.final
can be used to create non-constant values of built-in types, as well as classes and collections that are notconst
.
In general, use const
when you have a value that will never change and you want to ensure that only one instance of it exists, and use final
when you have a value that won’t change but can’t be known at compile time.
Example Usage
class MyClass {
final int a;
static const int b = 10;
MyClass(this.a);
void printValues() {
print('a: $a');
print('b: $b');
}
}
void main() {
final obj = MyClass(5);
obj.printValues();
}
In this example, we have a class MyClass
with two member variables a
and b
. a
is declared as final
, which means that it can only be assigned once, either in the constructor or when it’s declared. b
is declared as static const
, which means that it’s a compile-time constant and there is only one instance of it across all instances of the class.
In the constructor of MyClass
, we assign the value of a
. When we create an instance of MyClass
in main()
, we pass the value 5
to the constructor, which assigns it to a
.
Then, we call the method printValues()
, which prints the values of a
and b
. Since b
is declared as static const
, we can access it using the class name (MyClass.b
) instead of an instance of the class.
Overall, final
and const
are useful in classes to create immutable values that can’t be changed once they’re initialized. final
is used for values that can be initialized at runtime, while const
is used for values that can be initialized at compile-time.
Leave a Reply