Variables in Dart

Click "Run" on any code cell to execute it and see the results

Execution Mode:
Using backend server on port 3001

Variables in Dart


Definition

A variable is a named storage location that holds a value. In Dart, every variable has a type that determines what kind of data it can store. Variables allow you to store, retrieve, and manipulate data throughout your program.


Key Data Types


**int** - Integer Numbers

  • Whole numbers without decimal points
  • Range: -2^63 to 2^63 - 1
  • Example: -5, 0, 100, 42

  • **double** - Floating-Point Numbers

  • Numbers with decimal points
  • Used for precise calculations
  • Example: 3.14, 2.5, -0.001

  • **String** - Text Data

  • Sequences of characters
  • Use single or double quotes
  • Example: "Hello", 'Dart'

  • **bool** - Boolean Values

  • Only two possible values: true or false
  • Used for conditions and logic
  • Example: isActive = true

  • Variable Declaration Syntax

    `

    type variableName = value;

    `
    Cell2Dart
    // Basic variable assignment void main() { int age = 25; double height = 5.9; String name = "Alice"; bool isStudent = true; print('Name: $name'); print('Age: $age'); print('Height: $height'); print('Student: $isStudent'); }

    How Variables Work in Memory


    When you declare a variable:

    1. **Memory Allocation**: Dart reserves space in memory for the variable

    2. **Type Assignment**: The variable is assigned a type

    3. **Value Storage**: The value is stored at that memory location

    4. **Name Binding**: The variable name becomes a reference to that location


    Watch the right sidebar to see how variables are stored and modified!

    Cell4Dart
    // If-else example void main() { int score = 85; if (score >= 90) { print('Grade: A'); } else if (score >= 80) { print('Grade: B'); } else { print('Grade: F'); } }

    Important Concepts


    Scope

    Variables have scope - they only exist in the region where they are declared. In Dart, variables declared in curly braces {} only exist within those braces.


    Immutability

    You can create constant variables with `final` or `const` keywords, making them unchangeable after assignment.


    Type Inference

    Dart can infer the type of a variable using `var` keyword:

    `

    var message = "Hello"; // Dart infers this is a String

    var count = 42; // Dart infers this is an int

    `
    Cell6Dart
    // Type inference with var var name = "Dart"; // Inferred as String var count = 100; // Inferred as int var price = 19.99; // Inferred as double // Final variables (can't change after assignment) final greeting = "Welcome to Dart"; print('Name: $name'); print('Count: $count'); print('Price: $price'); print('Greeting: $greeting');

    Try It Yourself

    CellcustomDart
    // Modify this code and click Run int a = 10; int b = 20; print('Sum: ${a + b}');
    Run code to see variable values, call stack, and execution timeline here