Variables in Dart
In this lesson, you will learn how variables work in Dart. Variables are used to store real data such as user counts, prices, names, scores, and system values while your program is running.
In real-world applications, almost everything is stored in variables — from login information to product prices and API responses.
What Is a Variable?
A variable is a named container used to store a value in memory. That value can be read, updated, and reused throughout your program.
For example, an e-commerce app may store the total number of users, or a banking app may store an account balance.
Declaring a Variable
In Dart, variables are declared using a data type followed by a variable name.
int totalUsers = 1200;
print(totalUsers);
Here:
intspecifies the type (integer)totalUsersis the variable name1200is the stored value
Using Variables with Real Data
Let’s store information about a product in a shopping application.
String productName = "Wireless Mouse";
double productPrice = 29.99;
print(productName);
print(productPrice);
These variables represent real business data:
- Product name displayed to users
- Price used for billing and checkout
Updating Variable Values
Variables can change during program execution. For example, when a new user signs up, the user count increases.
int totalUsers = 1200;
totalUsers = totalUsers + 1;
print(totalUsers);
This reflects a real-world situation where data is continuously updated.
Using var Keyword
Dart allows you to use var instead of explicitly writing the data type.
The compiler automatically infers the type from the value.
var city = "San Francisco";
var temperature = 18.5;
print(city);
print(temperature);
Once assigned, the variable’s type cannot change.
Using final Variables
Use final when the value should be assigned only once.
This is common for fixed configuration values.
final String companyName = "Dataplexa";
print(companyName);
Trying to change a final variable will cause an error.
Using const Variables
const variables are compile-time constants.
They are used for values that never change, such as tax rates or fixed limits.
const double piValue = 3.14159;
print(piValue);
Variable Naming Rules
- Must start with a letter or underscore
- Cannot contain spaces
- Should be descriptive and readable
Good examples:
totalSalesuserEmailorderCount
📝 Practice Exercises
Exercise 1
Create a variable to store a student name and print it.
Exercise 2
Create a variable to store product price and update it.
Exercise 3
Create a constant variable for company country.
✅ Practice Answers
Answer 1
String studentName = "Amit";
print(studentName);
Answer 2
double price = 50.0;
price = 45.0;
print(price);
Answer 3
const String country = "USA";
print(country);
What’s Next?
Now that you understand how variables store and manage real data, the next lesson will introduce data types in Dart.
You will learn how Dart classifies values like numbers, text, and boolean data.