The const keyword in Dart is used to define compile-time constants. This means that the value of a const variable must be determined at compile-time and cannot be changed at runtime. Using const can help improve performance and reduce memory usage because the constant value is computed at compile-time and can be reused throughout the application.
const is used to define compile-time constants.const can be used with variables, objects, lists, maps, and constructors.const improves performance and reduces memory usage by reusing the same constant value throughout the application.const vs final: Use const for compile-time constants and final for runtime constants that are set once.void main() { // Const variable example const int age = 30; // 'age' is a compile-time constant // age = 31; // This will cause an error
const double pi = 3.14159; // 'pi' is a compile-time constant // pi = 3.14; // This will cause an error
print(age); // Output: 30 print(pi); // Output: 3.14159 }
When const is used with objects, the entire object and all of its properties must be constant. You can create a constant constructor for a class to enable creating compile-time constant instances of that class.
class Person { final String name; final int age;
// Const constructor const Person([this.name](<http://this.name/>), this.age); }