Dart Variables

Store and manipulate data in your Dart programs

📦 Dart Variables

Variables are containers that store data values in your program. In Dart, you can store different types of data like numbers, text, and boolean values using variables with descriptive names.


// Creating variables in Dart
void main() {
  var name = 'John';
  var age = 25;
  print('Hello $name, you are $age years old');
}
                                    

Output:

Hello John, you are 25 years old

Variable Types

var

var

Automatic type detection

var name = 'Alice';
String

String

Text data type

String message = 'Hello';
int

int

Whole numbers

int age = 30;
bool

bool

True or false values

bool isActive = true;

🔹 Creating Variables with var

The var keyword lets Dart automatically detect the data type:

void main() {
  // Dart automatically detects the type
  var studentName = 'Emma';        // String
  var studentAge = 20;             // int
  var studentHeight = 5.6;         // double
  var isEnrolled = true;           // bool
  
  // Print all variables
  print('Student: $studentName');
  print('Age: $studentAge');
  print('Height: $studentHeight feet');
  print('Enrolled: $isEnrolled');
}

Output:

Student: Emma

Age: 20

Height: 5.6 feet

Enrolled: true

🔹 Specific Data Types

You can also specify the exact data type for your variables:

🔸 String Variables

void main() {
  String firstName = 'John';
  String lastName = 'Smith';
  String fullName = firstName + ' ' + lastName;
  
  print('First Name: $firstName');
  print('Last Name: $lastName');
  print('Full Name: $fullName');
}

🔸 Number Variables

void main() {
  int wholeNumber = 42;           // Whole numbers
  double decimalNumber = 3.14;    // Decimal numbers
  num anyNumber = 100;            // Can be int or double
  
  print('Whole: $wholeNumber');
  print('Decimal: $decimalNumber');
  print('Any: $anyNumber');
}

🔸 Boolean Variables

void main() {
  bool isLoggedIn = true;
  bool hasPermission = false;
  
  print('Logged in: $isLoggedIn');
  print('Has permission: $hasPermission');
}

Output:

First Name: John

Last Name: Smith

Full Name: John Smith

Whole: 42

Decimal: 3.14

Any: 100

Logged in: true

Has permission: false

🔹 Variable Assignment and Updates

You can change the value of variables after creating them:

void main() {
  // Create and assign initial values
  var score = 0;
  var playerName = 'Player1';
  
  print('Initial score: $score');
  print('Player: $playerName');
  
  // Update variable values
  score = 100;
  playerName = 'SuperPlayer';
  
  print('Updated score: $score');
  print('Updated player: $playerName');
  
  // You can also update using operations
  score = score + 50;  // Add 50 to current score
  print('Final score: $score');
}

Output:

Initial score: 0

Player: Player1

Updated score: 100

Updated player: SuperPlayer

Final score: 150

🔹 Constants (final and const)

Use final and const for values that don't change:

🔸 final Variables

void main() {
  // final - set once, can't change later
  final String appName = 'My Dart App';
  final int maxUsers = 1000;
  
  print('App: $appName');
  print('Max users: $maxUsers');
  
  // This would cause an error:
  // appName = 'New Name'; // Error!
}

🔸 const Variables

void main() {
  // const - compile-time constant
  const double pi = 3.14159;
  const String version = '1.0.0';
  
  print('Pi: $pi');
  print('Version: $version');
  
  // Calculate area using const
  const double radius = 5.0;
  const double area = pi * radius * radius;
  print('Circle area: $area');
}

Output:

App: My Dart App

Max users: 1000

Pi: 3.14159

Version: 1.0.0

Circle area: 78.53975

🔹 Variable Naming Rules

Follow these rules when naming variables:

✅ Valid Variable Names:

  • Start with letter or underscore: name , _private
  • Use letters, numbers, underscores: user1 , first_name
  • Use camelCase: userName , totalScore

❌ Invalid Variable Names:

  • Start with number: 1name
  • Use spaces: user name
  • Use special characters: user@name , user-name
  • Use reserved words: class , if , for
void main() {
  // Good variable names
  var userName = 'alice123';
  var totalScore = 95;
  var isGameActive = true;
  var _privateData = 'secret';
  
  // Descriptive names are better
  var temperature = 25.5;  // Better than: var t = 25.5;
  var customerAge = 30;    // Better than: var a = 30;
  
  print('User: $userName, Score: $totalScore');
  print('Temperature: ${temperature}°C, Age: $customerAge');
}

Output:

User: alice123, Score: 95

Temperature: 25.5°C, Age: 30

🧠 Test Your Knowledge

Which keyword is used to create a variable with automatic type detection?