> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/NormandoRamirezDelgado/6C-Febrero-2026/llms.txt
> Use this file to discover all available pages before exploring further.

# Constants

> Learn about const and final keywords for creating immutable values in Dart

## 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?

<CardGroup cols={2}>
  <Card title="Safety" icon="shield">
    Prevent accidental modification of values that shouldn't change
  </Card>

  <Card title="Performance" icon="gauge-high">
    Compile-time constants are optimized by the compiler
  </Card>

  <Card title="Clarity" icon="lightbulb">
    Make your intent clear - this value is not meant to change
  </Card>

  <Card title="Debugging" icon="bug">
    Easier to track down errors when values are immutable
  </Card>
</CardGroup>

## const - Compile-Time Constants

The `const` keyword creates **compile-time constants**. These values must be known at compile time and are deeply immutable.

```dart theme={null}
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
}
```

<Note>
  **Naming Convention**: Constants are traditionally written in UPPERCASE letters to make them easily identifiable in code.
</Note>

### 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.

```dart theme={null}
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

<Accordion title="When to Use const">
  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

  ```dart theme={null}
  const PI = 3.14159;
  const MAX_USERS = 1000;
  const API_VERSION = '2.0';
  ```
</Accordion>

<Accordion title="When to Use final">
  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

  ```dart theme={null}
  final currentTime = DateTime.now();
  final userId = generateUserId();
  final userName = getUserInput();
  ```
</Accordion>

## Attempting to Modify Constants

<Warning>
  Both `const` and `final` values cannot be reassigned. Attempting to do so will result in a compile-time error.
</Warning>

```dart theme={null}
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:

```dart theme={null}
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}');
}
```

<Tip>
  Use `$variableName` for simple variable interpolation, and `${expression}` for expressions or method calls.
</Tip>

## Practical Examples

### Mathematical Constants

```dart theme={null}
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

```dart theme={null}
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

```dart theme={null}
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

<Check>
  **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
</Check>

<Warning>
  **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)
</Warning>

## Complete Example

```dart theme={null}
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.
