Constants in Dart

Constants in Dart

Dart supports constants of character, string, boolean, and numeric values.

// Declaring a constant value.
const String s = "constant";

void main() {
  print(s);

  // A const statement can appear anywhere a var statement can.
  const int n = 500000000;

  // Constant expressions perform arithmetic with arbitrary precision.
  const double d = 3e20 / n;
  print(d);

  // A numeric constant has no type until it’s given one, such as by an explicit conversion.
  print(d.toInt());

  // A number can be given a type by using it in a context that requires one, such as a variable assignment or function call.
  // For example, here `sin` from 'dart:math' expects a `double`.
  import 'dart:math';
  print(sin(n));
}

To run the Dart program, save the code in a file named constants.dart and use the dart command to execute it.

$ dart run constants.dart
constant
6e+11
600000000000
-0.28470407323754404

Now that we can run and build basic Dart programs, let’s learn more about the language.