Variables in Dart

Variables are used to store data that can be used and modified later in your program. In Dart, you can declare variables using var, final, const, or explicit types.

Declaring Variables

Dart provides several ways to declare variables:

Using var

The var keyword lets Dart automatically determine the type of your variable based on the value you assign:

var name = 'Alice';        // String
var age = 25;              // int
var height = 5.8;          // double
var isStudent = true;      // bool

Using Specific Types

You can explicitly specify the type of your variable:

String city = 'New York';
int population = 8000000;
double temperature = 23.5;
bool isRaining = false;

Using dynamic

The dynamic keyword allows a variable to hold any type of value and can change types during runtime:

dynamic value = 42;
value = 'Hello';           // Now it's a String
value = true;              // Now it's a bool

Variable Naming Rules

When naming variables in Dart, follow these rules:

  • Start with a letter or underscore
  • Can contain letters, numbers, and underscores
  • Cannot use Dart keywords (like var, if, for, etc.)
  • Use camelCase for better readability
// Good variable names
var firstName = 'John';
var userAge = 30;
var _privateVariable = 'secret';

// Bad variable names (avoid these)
// var 2name = 'John';     // Cannot start with number
// var if = 'condition';   // Cannot use keywords

Final and Const Variables

final

Use final for variables that you want to set only once:

final String country = 'USA';
final currentTime = DateTime.now();
// country = 'Canada';  // This would cause an error

const

Use const for compile-time constants:

const double pi = 3.14159;
const int maxUsers = 100;

Variable Initialization

Variables can be initialized when declared or later in the code:

// Initialize when declaring
var score = 0;

// Declare first, initialize later
int lives;
lives = 3;

// Using late keyword for late initialization
late String username;
username = 'player1';

Printing Variables

While printing variables along with text using print, you can use the $ symbol for interpolation:

void main() {
  var apples = 5;
  print('I have $apples apples in total.');
}

Best Practices

  1. Use descriptive names: userAge is better than a
  2. Initialize variables: Avoid null-related errors
  3. Use final when possible: Makes your code more predictable
  4. Choose appropriate types: Use int for whole numbers, double for decimals

Variables are the foundation of any program - they help you store, manipulate, and work with data throughout your Dart applications!