Dart Constants: Immutable Values in Dart Programming
Learn Dart through interactive, bite-sized lessons. Build Flutter apps and master modern development.
Start Dart Journey →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.
Declaring Constants in Dart
Dart provides two ways to declare constants:
1. Using the 'const' keyword
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];
2. Using the 'final' keyword
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();
Benefits of Using Constants
- Improved code readability
- Prevention of accidental value changes
- Potential performance optimizations by the Dart compiler
- Clearer intent in your code
Best Practices for Dart Constants
- Use
constfor values known at compile time - Prefer
finalfor runtime constants - Name constants in SCREAMING_SNAKE_CASE for better visibility
- Group related constants in a class for better organization
Constants in Classes
You 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
Const Constructors
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);
}
Conclusion
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.