Constants in Dart are immutable values that remain unchanged throughout the execution of a program. They play a crucial role in writing efficient and error-free code. Let's explore how to use constants in Dart and why they're important.
Dart provides two ways to declare constants:
The const
keyword is used for compile-time constants. These are values that are known at compile time and cannot change.
const pi = 3.14159;
const String greeting = 'Hello, Dart!';
const List<int> primes = [2, 3, 5, 7, 11];
The final
keyword is used for runtime constants. These are values that are set once and cannot be changed afterward, but they don't need to be known at compile time.
final currentTime = DateTime.now();
final String username = getUserInput();
const
for values known at compile timefinal
for runtime constantsYou can also use constants within classes. Here's an example:
class Colors {
static const RED = '#FF0000';
static const GREEN = '#00FF00';
static const BLUE = '#0000FF';
}
Access these constants using the class name: Colors.RED
Dart allows you to create immutable objects using const constructors. This is particularly useful when working with Dart Classes and Dart Objects.
class Point {
final int x;
final int y;
const Point(this.x, this.y);
}
void main() {
const origin = Point(0, 0);
}
Constants are a powerful feature in Dart that help create more robust and efficient code. By understanding when and how to use const
and final
, you can write cleaner, more maintainable Dart programs. As you continue your Dart journey, explore how constants interact with other language features like Dart Data Types and Dart Variables.