Dart Variables
A variable in Dart gives a name to a value used by a program. Dart is type-safe, but it can often infer a variable’s type from its initial value, so an explicit type declaration is not always required.
Dart variables can be declared with var, an explicit data type, dynamic, final, or const. The appropriate declaration depends on whether the value can change and whether its type should be checked at compile time.
Declare a Dart Variable with var
You can declare a variable using the var keyword.
var a;
When var is used without an initializer, as in the statement above, the variable has the type dynamic. A local variable must be assigned a value before it is read.
void main() {
var message;
message = 'Hello';
print(message);
}
Hello
Initialize a Dart Variable with a Value
You can initialize a variable by assigning a value with the assignment operator =.
var a = 'Hello World';
In this declaration, Dart infers that a has the type String because its initial value is a string. The inferred type remains fixed, so assigning an integer to a later would produce a compile-time error.
void main() {
var language = 'Dart';
var version = 3;
var isTypeSafe = true;
print(language);
print(version);
print(isTypeSafe);
}
Dart
3
true
Declare a Dart Variable with an Explicit Type
You can write the variable’s data type explicitly instead of using var. Explicit types can make the intended kind of value clearer, especially in public APIs and declarations where the initializer does not make the type obvious.
String a = 'Hello World';
Common built-in Dart types include int, double, num, String, bool, List, Set, and Map.
void main() {
String name = 'Arun';
int age = 24;
double height = 1.75;
bool isStudent = false;
print('$name, $age, $height, $isStudent');
}
Arun, 24, 1.75, false
Change the Value of a Dart Variable
A variable declared with var or an explicit type can be assigned a new value of the same compatible type.
void main() {
var score = 60;
score = 85;
print(score);
}
85
Because score is inferred as an int, it cannot later hold a String value.
Use dynamic for Values of Different Types
A variable declared with the dynamic keyword can reference values of different types during its lifetime. Operations on a dynamic value are generally checked at runtime rather than fully checked at compile time.
void main(){
dynamic a = 'Hello World';
a = 10;
}
In this example, a initially contains a String and is then assigned an int. Use dynamic only when values genuinely need to have different types, because excessive use reduces compile-time type checking.
Difference Between var and dynamic in Dart
The main difference depends on whether an initial value is provided. A variable declared with var and an initializer receives a specific inferred type. A variable declared with dynamic can be assigned values of unrelated types.
| Declaration | Type behavior | Different value types allowed later? |
|---|---|---|
var count = 10; | Inferred as int | No |
var value; | Uses dynamic when no type or initializer is supplied | Yes |
dynamic value = 10; | Explicitly dynamic | Yes |
int count = 10; | Explicitly int | No |
Use final for a Value Assigned Once
A final variable can be assigned only once. Its value may be determined while the program is running.
void main() {
final currentTime = DateTime.now();
final String course = 'Dart Basics';
print(course);
print(currentTime);
}
After a final variable has been initialized, another value cannot be assigned to it.
Use const for a Compile-Time Constant
A const variable represents a compile-time constant. Its value must be known before the program runs.
void main() {
const double pi = 3.14159;
const int daysInWeek = 7;
print(pi);
print(daysInWeek);
}
Use final when a value is assigned once at runtime. Use const when the value is fixed and available at compile time.
Nullable and Non-Nullable Dart Variables
With Dart null safety, a variable is non-nullable by default. A non-nullable variable cannot contain null. Add ? to the type when null is a valid value.
void main() {
String username = 'Maya';
String? middleName;
print(username);
print(middleName);
}
Maya
null
Here, username must contain a String, while middleName can contain either a String or null.
Declare Multiple Dart Variables
Variables of the same explicit type can be declared in one statement. Separate declarations are often easier to read when the variables have different purposes or initial values.
void main() {
int width = 10, height = 5;
int area = width * height;
print(area);
}
50
Dart Variable Naming Rules
- A variable name can contain letters, digits, underscores, and dollar signs.
- A variable name cannot begin with a digit.
- Dart variable names are case-sensitive, so
scoreandScoreare different names. - Reserved Dart keywords cannot be used as variable names.
- Use lower camel case for ordinary variable names, such as
totalPriceorstudentName. - Choose names that describe the stored value instead of unclear names such as
xordata, except in small, well-defined contexts.
Local, Instance, and Top-Level Variables in Dart
A variable’s location determines where it can be accessed.
- Local variable: Declared inside a function or block and available only within that scope.
- Instance variable: Declared inside a class but outside its methods. Each class object can have its own value.
- Top-level variable: Declared outside classes and functions and available to code in the same Dart library.
- Static variable: Declared with
staticinside a class and shared by all instances of that class.
String applicationName = 'Store App';
class Product {
static int productCount = 0;
String name;
Product(this.name) {
productCount++;
}
}
void main() {
var product = Product('Keyboard');
var localMessage = 'Product created';
print(applicationName);
print(product.name);
print(Product.productCount);
print(localMessage);
}
Common Errors When Declaring Dart Variables
- Reading an unassigned local variable: Assign a value before using the variable.
- Assigning an incompatible type: A variable inferred or declared as
intcannot hold aString. - Assigning null to a non-nullable variable: Use a nullable type such as
String?only when null is meaningful. - Reassigning final or const: Variables declared with
finalorconstcannot receive another value. - Using dynamic unnecessarily: Prefer inferred or explicit types when the value has a predictable type.
Dart Variables Example Program
void main() {
String productName = 'Laptop';
var quantity = 2;
double unitPrice = 750.0;
final orderId = 'ORD-104';
const double taxRate = 0.08;
String? couponCode;
double subtotal = quantity * unitPrice;
double tax = subtotal * taxRate;
double total = subtotal + tax;
print('Order: $orderId');
print('Product: $productName');
print('Quantity: $quantity');
print('Coupon: $couponCode');
print('Total: \$$total');
}
Order: ORD-104
Product: Laptop
Quantity: 2
Coupon: null
Total: $1620.0
Dart Variables Frequently Asked Questions
What is a variable in Dart?
A variable is a named reference to a value. It allows a Dart program to store, access, and update data while the program runs.
Does Dart require a type for every variable?
Dart variables always have types, but you do not always need to write those types explicitly. Dart can infer a type when a variable declared with var has an initial value.
Can a var variable change its data type in Dart?
A var variable initialized with a value cannot later change to an unrelated type. For example, var count = 1; is inferred as int. However, var value; has the type dynamic because no initializer or explicit type is provided.
What is the difference between final and const in Dart?
Both can be assigned only once. A final value may be determined at runtime, while a const value must be known at compile time.
How do I allow null in a Dart variable?
Add a question mark to the type, such as String? or int?. This declares that the variable may contain either a value of that type or null.
Summary of Dart Variable Declarations
Use var when Dart can clearly infer a fixed type, an explicit type when it improves clarity, and dynamic only when values must have different types. Use final for a value assigned once at runtime and const for a compile-time constant. Under Dart null safety, add ? only when a variable is intended to accept null.
In this Dart Tutorial, we learned how to declare, initialize, update, and type Dart variables, as well as how var, dynamic, final, const, and nullable types differ.
TutorialKart.com