Dart Variables


In Dart, variables are used to store and manage data. Dart is a statically-typed language, meaning that every variable has a specific type determined either explicitly or inferred. Dart supports several ways of declaring variables, including with keywords like var, final, and const, allowing flexibility in managing data that is mutable or immutable.


1. Declaring Variables

Dart offers multiple ways to declare variables, and each has its own use case:

a. Using var

  • When you declare a variable with var, Dart infers its type based on the initial value assigned.
  • Once a type is assigned to a variable using var, it cannot be changed.
void main() { var name = "Alice"; // Dart infers `name` as String var age = 30; // Dart infers `age` as int // name = 123; // Error: A string can't be assigned an int print('$name is $age years old.'); }

b. Using Explicit Type

  • You can also declare a variable with an explicit type (e.g., int, String, double, bool).
  • This is useful when you want to make the type clear or enforce a specific data type.
void main() { String greeting = "Hello"; int year = 2024; bool isActive = true; print('$greeting, year: $year, active: $isActive'); }

c. Using final

  • final is used to declare variables whose values can only be set once and cannot be reassigned afterward.
  • Unlike const, final allows for runtime initialization.
void main() { final country = "USA"; // country = "Canada"; // Error: Cannot change a final variable print(country); }

d. Using const

  • const variables are compile-time constants. This means that their values must be known and set at compile time.
  • const variables cannot be reassigned, and their values are immutable.
void main() { const pi = 3.14159; // pi = 3.14; // Error: Cannot change a const variable print(pi); }

2. Types of Variables

Dart supports several data types that can be used for variables:

  • String: Used to store text. Strings can be single or double-quoted.

    String name = 'Alice';
  • int: Used to store integer values.

    int age = 30;
  • double: Used for floating-point numbers.

    double temperature = 98.6;
  • bool: Used to store boolean values (true or false).

    bool isValid = true;
  • List: A collection of ordered items (similar to an array).

    List<String> colors = ['red', 'green', 'blue'];
  • Map: A collection of key-value pairs.

    Map<String, int> scores = {'Alice': 100, 'Bob': 95};

3. Nullable and Non-Nullable Variables

By default, variables in Dart are non-nullable, which means they cannot contain null unless explicitly specified with ?.

  • Non-nullable:

    int age = 30; // Cannot be null
  • Nullable: Add ? to the type, allowing it to hold null.

    int? age = null; // Can be null

4. Late Initialization

The late modifier allows for declaring non-nullable variables without initializing them immediately. This is useful when a variable’s value is determined later but guaranteed before usage.

void main() { late String description; // Assigning value later description = "This is a late-initialized variable"; print(description); }

5. Variable Scope

Dart variables have scope, which defines where they can be accessed.

  • Local Variables: Declared within a function or block, accessible only within that function or block.
  • Global Variables: Declared outside of any function, accessible throughout the entire file.
// Global variable String globalVar = 'I am global'; void main() { // Local variable String localVar = 'I am local'; print(globalVar); print(localVar); }

6. Type Inference

Dart’s var keyword enables type inference. Dart automatically infers the type based on the assigned value, which reduces the need for explicit typing.

void main() { var name = "Alice"; // Dart infers as String var age = 25; // Dart infers as int }

If you want a variable with a dynamic type (that can hold any type of value), use dynamic:

void main() { dynamic variable = "Hello"; variable = 123; // No error }

Summary

  • var: Automatically infers type, can’t change type later.
  • final: Immutable, single-assignment, set at runtime.
  • const: Compile-time constant, immutable.
  • Explicit Type: Define the type directly (int, String, etc.).
  • Nullable Types: Use ? to allow null values.
  • late: Allows delayed initialization of non-nullable variables.

Understanding Dart’s variable syntax and modifiers is crucial to managing data effectively in Dart applications, providing flexibility for both mutable and immutable values across various data types.