Sobes.tech
Middle

Millised on viis kasutada Dartis võtmesõna const?

sobes.tech AI

Vastus AI-lt

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 at compile time.

    const int speedOfLight = 299792458; // Constant value
    
  2. As a constructor modifier: A constructor marked as const creates immutable class instances 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 execution and cannot be changed afterward.
Characteristics const final
Initialization time At compile time At runtime (once)
Mutability 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)