DEV Community

Geoffrey Kim
Geoffrey Kim

Posted on

Understanding Variables in Dart: A Comprehensive Guide

The Var Keyword

  1. var
    • There is no need to specify the variable's type.
    • When updating the value, it must match the original type of the variable.
  2. Explicit Declaration
    • Conventionally, the var keyword is used to declare local variables within functions or methods (recommended by the Dart style guide, as the compiler knows the type anyway).
    • When declaring variables or properties in a class, the type is specified.

Dynamic Type

  • A keyword used for variables that can have various types.
  • It's not generally recommended, but it can be very useful at times.
  • Why? It is used when it is difficult to know what type a variable will be, especially when working with Flutter or JSON.
  • Example of usage:
void main() {
  var a;
  dynamic b;
}
Enter fullscreen mode Exit fullscreen mode

Nullable Variables

Null safety prevents the developer from referencing null values.
In Dart, it must be clearly indicated whether a variable can be null.

void main() {
  String? nico = 'nico';
  nico = null;
  nico?.isNotEmpty; // This checks if the value exists before proceeding with the following operations. Equivalent to the below.
  if (nico != null) {
    nico.isNotEmpty;
  }
}
Enter fullscreen mode Exit fullscreen mode

Final Variables

To define a variable that cannot be modified, use final instead of var.
It's similar to const in JavaScript or TypeScript.

void main() {
  final a = 'nico';
  final String b = 'nico';
}
Enter fullscreen mode Exit fullscreen mode

Late Variables

late is a modifier that can be added before final or var.
late allows declaring a variable without initial data.

void main() {
  late final String name;
  // do something, go to api
  name = 'nico';
}
Enter fullscreen mode Exit fullscreen mode

Constant Variables

const in Dart is different from JavaScript or TypeScript.
In JavaScript or TypeScript, const is similar to final in Dart.
In Dart, const is used to create compile-time constants.
It's used for values that are known at compile time.
These values are known before uploading the app to the app store.

void main() {
  const name = 'nico';
  const max_allowed_price = 120;
}
Enter fullscreen mode Exit fullscreen mode

Recap

According to Dart's style guide, it is recommended to use var as much as possible, and using types is advised when writing properties in a class. When declaring local variables within methods or small functions, using var is preferable since the compiler will infer the variable's type anyway.

The dynamic type must be used very cautiously.

References

https://nomadcoders.co/dart-for-beginners

Top comments (0)