Dart Constants
Creating immutable values in Dart
🔒 What are Dart Constants?
Constants in Dart are immutable values that cannot be changed after creation. Use 'final' for runtime constants and 'const' for compile-time constants to ensure data integrity.
// Constant examples
final String name = 'Alice';
const int maxUsers = 100;
print(name); // Output: Alice
Types of Constants
final
Runtime constants, set once
final String name = 'John';
const
Compile-time constants
const int maxValue = 100;
static const
Class-level constants
static const String version = '1.0';
Immutable
Cannot be reassigned
final list = [1, 2, 3];
// list = [4, 5, 6]; // Error!
🔹 final vs const
Understanding the difference between final and const:
// final - runtime constant
final String currentTime = DateTime.now().toString();
final int randomNumber = Random().nextInt(100);
// const - compile-time constant
const String appName = 'My App';
const int maxRetries = 3;
const double pi = 3.14159;
print('App: $appName');
print('Max retries: $maxRetries');
print('Pi: $pi');
print('Current time: $currentTime');
// const must be known at compile time
// const String badExample = DateTime.now().toString(); // Error!
Output:
App: My App
Max retries: 3
Pi: 3.14159
Current time: 2024-01-15 10:30:45.123
Max retries: 3
Pi: 3.14159
Current time: 2024-01-15 10:30:45.123
🔹 Constant Collections
Creating immutable lists, sets, and maps:
// Constant list
const List<String> colors = ['red', 'green', 'blue'];
print('Colors: $colors');
// Constant set
const Set<int> primeNumbers = {2, 3, 5, 7, 11};
print('Primes: $primeNumbers');
// Constant map
const Map<String, int> scores = {
'Alice': 95,
'Bob': 87,
'Charlie': 92
};
print('Scores: $scores');
// These collections cannot be modified
// colors.add('yellow'); // Error!
// primeNumbers.add(13); // Error!
// scores['David'] = 88; // Error!
Output:
Colors: [red, green, blue]
Primes: {2, 3, 5, 7, 11}
Scores: {Alice: 95, Bob: 87, Charlie: 92}
Primes: {2, 3, 5, 7, 11}
Scores: {Alice: 95, Bob: 87, Charlie: 92}
🔹 Class Constants
Using constants in classes:
class MathConstants {
static const double pi = 3.14159;
static const double e = 2.71828;
static const int maxInt = 9223372036854775807;
// Instance constants
final String name;
final DateTime createdAt;
MathConstants(this.name) : createdAt = DateTime.now();
}
// Using class constants
print('Pi: ${MathConstants.pi}');
print('E: ${MathConstants.e}');
print('Max Int: ${MathConstants.maxInt}');
// Creating instance with final values
MathConstants math = MathConstants('Calculator');
print('Name: ${math.name}');
print('Created: ${math.createdAt}');
Output:
Pi: 3.14159
E: 2.71828
Max Int: 9223372036854775807
Name: Calculator
Created: 2024-01-15 10:30:45.456
E: 2.71828
Max Int: 9223372036854775807
Name: Calculator
Created: 2024-01-15 10:30:45.456
🔹 Benefits of Constants
Why use constants in your code:
Performance Benefits:
- Memory Efficiency: const values are stored once in memory
- Compile-time Optimization: const values are optimized during compilation
- Faster Access: No need to compute values at runtime
Code Quality Benefits:
- Immutability: Prevents accidental changes to important values
- Readability: Makes code intentions clear
- Maintainability: Central place to define important values
// Good practice: Use constants for configuration
class AppConfig {
static const String appName = 'My Flutter App';
static const String version = '1.0.0';
static const int maxFileSize = 1024 * 1024; // 1MB
static const List<String> supportedFormats = ['jpg', 'png', 'gif'];
}
// Usage
print('Welcome to ${AppConfig.appName} v${AppConfig.version}');
print('Max file size: ${AppConfig.maxFileSize} bytes');
print('Supported formats: ${AppConfig.supportedFormats}');
Output:
Welcome to My Flutter App v1.0.0
Max file size: 1048576 bytes
Supported formats: [jpg, png, gif]
Max file size: 1048576 bytes
Supported formats: [jpg, png, gif]