Skip to main content

Introduction

In Dart, constants are values that cannot be changed after they’re set. Using constants makes your code safer, more efficient, and easier to understand. Dart provides two keywords for creating constants: const and final.

Why Use Constants?

Safety

Prevent accidental modification of values that shouldn’t change

Performance

Compile-time constants are optimized by the compiler

Clarity

Make your intent clear - this value is not meant to change

Debugging

Easier to track down errors when values are immutable

const - Compile-Time Constants

The const keyword creates compile-time constants. These values must be known at compile time and are deeply immutable.
void main() {
  // const: Compile-time constants
  const NUMERO = 12;
  const REAL = 234234.2345345;
  const PI = 3.14159;
  const VELOCIDAD_LUZ = 299792458;
  
  print('Valor de PI: $PI');  // String interpolation
  print(VELOCIDAD_LUZ);       // 299792458
  print(NUMERO);              // 12
  print(REAL);                // 234234.2345345
}
Naming Convention: Constants are traditionally written in UPPERCASE letters to make them easily identifiable in code.

Const Characteristics

  • Must be assigned a value at compile time
  • The value must be a compile-time constant expression
  • Cannot be reassigned
  • More memory efficient (values are canonicalized)

What Can Be const?

Valid const values:
  • Numbers: const MAX_SIZE = 100;
  • Strings: const APP_NAME = 'MyApp';
  • Booleans: const IS_DEBUG = false;
  • Other const values: const DOUBLE_MAX = MAX_SIZE * 2;
Cannot be const:
  • Function calls (except const constructors)
  • Values computed at runtime
  • User input
  • Current date/time

final - Runtime Constants

The final keyword creates runtime constants. The value is set once when first accessed and cannot be changed afterward, but it doesn’t need to be known at compile time.
void main() {
  // final: Runtime constant (value set when first accessed)
  final fechaActual = DateTime.now();
  print('La Fecha Actual es: $fechaActual');
  
  // fechaActual = DateTime.now();  // ❌ ERROR: Cannot reassign
}

Final Characteristics

  • Can be set at runtime
  • Value can be the result of a function or computation
  • Cannot be reassigned after initialization
  • Each object can have its own final value

const vs final: Key Differences

Use const when:
  • The value is known at compile time
  • You want maximum performance optimization
  • The value is truly universal and unchanging (like PI, mathematical constants)
  • You’re defining configuration values that never change
const PI = 3.14159;
const MAX_USERS = 1000;
const API_VERSION = '2.0';
Use final when:
  • The value is determined at runtime
  • The value comes from a function call or calculation
  • Each instance needs its own immutable value
  • You want to prevent reassignment but the initial value isn’t known until runtime
final currentTime = DateTime.now();
final userId = generateUserId();
final userName = getUserInput();

Attempting to Modify Constants

Both const and final values cannot be reassigned. Attempting to do so will result in a compile-time error.
void main() {
  const VELOCIDAD_LUZ = 299792458;
  
  // ❌ ERROR: Constants can't be assigned a value
  // VELOCIDAD_LUZ = 300000000;  // This will not compile!
  
  final fecha = DateTime.now();
  
  // ❌ ERROR: Final variables can't be assigned a value more than once
  // fecha = DateTime.now();  // This will not compile!
}

String Interpolation with Constants

You can embed constant values directly in strings using the $ symbol:
void main() {
  const PI = 3.14159;
  const VELOCIDAD_LUZ = 299792458;
  
  // String interpolation
  print('Valor de PI: $PI');
  print('La velocidad de la luz es: $VELOCIDAD_LUZ m/s');
  
  // For expressions, use ${}
  print('El área del círculo con radio 5 es: ${PI * 5 * 5}');
}
Use $variableName for simple variable interpolation, and ${expression} for expressions or method calls.

Practical Examples

Mathematical Constants

void main() {
  const PI = 3.14159;
  const E = 2.71828;
  const GOLDEN_RATIO = 1.61803;
  
  print('PI: $PI');
  print('Euler\'s number: $E');
  print('Golden Ratio: $GOLDEN_RATIO');
}

Configuration Values

void main() {
  const APP_VERSION = '1.0.0';
  const MAX_LOGIN_ATTEMPTS = 3;
  const DEFAULT_TIMEOUT = 30;
  
  print('App Version: $APP_VERSION');
  print('Maximum login attempts: $MAX_LOGIN_ATTEMPTS');
  print('Default timeout: $DEFAULT_TIMEOUT seconds');
}

Runtime Values

void main() {
  // These must be final because they're computed at runtime
  final currentDate = DateTime.now();
  final timestamp = DateTime.now().millisecondsSinceEpoch;
  
  print('Current date: $currentDate');
  print('Timestamp: $timestamp');
}

Best Practices

Do:
  • Use UPPERCASE for const values to make them easily identifiable
  • Use camelCase for final values (they behave like regular variables)
  • Choose const over final when possible for better performance
  • Use descriptive names that indicate the constant’s purpose
  • Group related constants together
Don’t:
  • Use const for runtime values (use final instead)
  • Overuse dynamic with constants (defeats the purpose of type safety)
  • Use ambiguous names like NUM1, VALUE, etc.
  • Try to modify constant values (it won’t compile)

Complete Example

void main() {
  // Compile-time constants (UPPERCASE)
  const PI = 3.14159;
  const VELOCIDAD_LUZ = 299792458;  // Speed of light in m/s
  const MAX_USUARIOS = 100;
  
  // Runtime constants (camelCase)
  final fechaInicio = DateTime.now();
  final nombreApp = 'Mi Aplicación';
  
  // Using constants
  print('=== Constantes ===');
  print('PI: $PI');
  print('Velocidad de la luz: $VELOCIDAD_LUZ m/s');
  print('Máximo de usuarios: $MAX_USUARIOS');
  print('\n=== Valores Finales ===');
  print('Aplicación: $nombreApp');
  print('Iniciada: $fechaInicio');
  
  // Calculate circle area
  final radio = 10;
  final area = PI * radio * radio;
  print('\nÁrea del círculo con radio $radio: $area');
}

Key Takeaways

  • Use const for compile-time constants (values known before runtime)
  • Use final for runtime constants (values set once at runtime)
  • Constants cannot be reassigned after their initial value is set
  • Use UPPERCASE for const, camelCase for final
  • Constants improve code safety, performance, and readability
  • String interpolation works with both const and final values

Next Steps

Now that you understand constants, you’re ready to learn about type conversions and how to transform data from one type to another.

Build docs developers (and LLMs) love