Variables in Dart

In Dart, variables are declared and can be type-inferred or explicitly typed. Let’s explore various ways to declare and use variables in Dart.

void main() {
  // var declares a variable with type inference
  var a = "initial";
  print(a);

  // You can declare multiple variables at once
  int b = 1, c = 2;
  print('$b $c');

  // Dart will infer the type of initialized variables
  var d = true;
  print(d);

  // Variables declared without initialization are null by default
  int e;
  print(e);

  // The final keyword is used for variables that don't change after initialization
  final f = "apple";
  print(f);
}

To run this Dart program:

$ dart run variables.dart
initial
1 2
true
null
apple

In Dart:

  • The var keyword is used for type inference, allowing the compiler to determine the type based on the assigned value.
  • You can explicitly declare types for variables (like int b = 1).
  • Variables declared without initialization are null by default, unlike Go where they have zero values.
  • Dart uses final for variables that won’t change after initialization, which is somewhat similar to the := syntax in Go for declaring and initializing variables within functions.
  • String interpolation is done using $variable or ${expression} within string literals.

Dart’s approach to variables provides flexibility while maintaining type safety, allowing developers to write clean and efficient code.