Sobes.tech
Middle

What are the ways to use the const keyword in Dart?

sobes.tech AI

Answer from AI

The const keyword in Dart is used to create constant values that are determined at compile time and cannot be changed during program execution.

Usage methods:

  1. As a variable modifier: Used to declare a variable whose value is constant during compilation.

    const int speedOfLight = 299792458; // Constant value
    
  2. As a constructor modifier: A constructor declared as const creates immutable instances of a class if all its fields are final (final) or constant (const).

    class Point {
      final double x;
      final double y;
    
      const Point(this.x, this.y); // Constant constructor
    }
    
    const origin = Point(0.0, 0.0); // Creating a constant instance
    
  3. For creating constant collections: Used to create lists, sets, and maps whose contents are constant during compilation.

    const List<int> primeNumbers = [2, 3, 5, 7, 11]; // Constant list
    const Set<String> constants = {'pi', 'e', 'phi'}; // Constant set
    const Map<String, double> mathConstants = {
      'pi': 3.14159,
      'e': 2.71828
    }; // Constant map
    
  4. In contexts where a constant value is expected: For example, when creating widgets in Flutter, where constant widgets can be optimized.

    // In Flutter context
    const Text('Hello, World!'); // Constant widget
    

Differences from final:

  • const defines a value known at compile time.
  • final defines a value that is assigned only once during runtime and cannot be changed afterward.
Characteristic const final
Initialization time At compile time At runtime (once)
Immutability of value Immutable Assigned once, then immutable
Application to instances Creates a constant instance (if constructor is const) Creates an immutable reference to an object
Application to collections Creates an immutable collection with immutable content Creates an immutable reference to a collection (content can be mutable)
What are the ways to use the const keyword in Dart… - sobes.tech