Introduction
In programming, variables are the building blocks of any application. They act as containers for storing data values which can be changed and manipulated throughout the program. Dart, the programming language behind Flutter, provides a flexible and modern approach to declaring and using variables, making it easy for developers to write clean and efficient code.
Understanding variables in Dart is essential for any beginner who wants to build applications, whether it’s a simple console app or a complex Flutter mobile app. This article will guide you through types of variables, declaration methods, scope, data types, best practices, and practical examples to ensure you have a strong foundation.
What is a Variable?
A variable is a named storage that holds data which can be modified during program execution. Think of it as a labeled box where you can store and retrieve information.
In Dart, every variable has a type, either explicitly declared or inferred by the compiler. The type defines what kind of data can be stored, such as numbers, text, or boolean values.
Variable Declaration in Dart
Dart offers multiple ways to declare variables, giving you flexibility and control over how you manage data.
1. Using var
The var keyword allows Dart to infer the type of the variable from the value you assign.
Example:
void main() {
var name = 'Flutter'; // Dart infers this is a String
var version = 3.7; // Dart infers this is a double
print('Framework: $name');
print('Version: $version');
}
Key points:
- Type is inferred automatically.
- Once the type is inferred, it cannot change.
- Ideal for variables with initial values.
2. Using final
The final keyword is used to declare a variable whose value cannot change once assigned. However, unlike const, the value can be determined at runtime.
Example:
void main() {
final framework = 'Flutter';
final version = 3.7;
print('Framework: $framework, Version: $version');
}
Key points:
- Value is immutable once assigned.
- Can be assigned at runtime.
- Useful for constants that are only known during program execution.
3. Using const
The const keyword is used for compile-time constants, meaning the value must be known during compilation.
Example:
void main() {
const pi = 3.14159;
const appName = 'HelloWorld';
print('App: $appName, Pi: $pi');
}
Key points:
- Value must be known at compile time.
- Cannot change during program execution.
- More memory-efficient because
constvariables are canonicalized (shared in memory).
4. Using Explicit Types
You can explicitly define the type of a variable instead of letting Dart infer it. This is useful for readability and catching errors early.
Example:
void main() {
String name = 'Dart';
int year = 2025;
double version = 3.7;
bool isStable = true;
print('$name $version is stable: $isStable, Released: $year');
}
Advantages of Explicit Types:
- Enhances code readability.
- Helps Dart catch type errors during compilation.
- Important for team projects and maintainable code.
Common Data Types in Dart
Dart provides a wide range of data types to store different kinds of information:
- Numbers
int→ Whole numbers (e.g., 1, -42, 1000)double→ Decimal numbers (e.g., 3.14, -0.001)
- Strings
- Textual data enclosed in single or double quotes.
String greeting = 'Hello, Dart!'; - Boolean
- Represents
trueorfalse.
bool isFlutterFun = true; - Represents
- List
- Ordered collection of elements.
List<int> numbers = [1, 2, 3, 4]; - Map
- Key-value pairs.
Map<String, String> capitals = {'Pakistan': 'Islamabad', 'USA': 'Washington D.C.'}; - Dynamic
- Can store any type, but not recommended unless necessary.
dynamic variable = 'Hello'; variable = 42;
Variable Scope in Dart
Scope determines where a variable can be accessed within a program. Dart has three main types of variable scope:
1. Local Variables
Declared inside a function or block and accessible only there.
void main() {
var message = 'Hello World'; // Local to main()
print(message);
}
2. Global Variables
Declared outside any function and accessible throughout the file.
String globalMessage = 'I am Global';
void main() {
print(globalMessage);
}
3. Static Variables
Declared inside a class with the static keyword. They are shared across all instances of the class.
class Counter {
static int count = 0;
void increment() {
count++;
}
}
void main() {
var c1 = Counter();
var c2 = Counter();
c1.increment();
c2.increment();
print('Count: ${Counter.count}'); // Output: Count: 2
}
Naming Rules for Dart Variables
- Names must start with a letter or underscore.
- Cannot start with a number.
- Cannot use Dart reserved keywords.
- Use camelCase for readability.
Valid examples:
var myName;
var _hiddenValue;
var userAge;
Invalid examples:
var 1stName; // Starts with a number
var class; // Reserved keyword
Declaring Multiple Variables
You can declare multiple variables of the same type in a single line:
int x = 10, y = 20, z = 30;
Or using var:
var a = 5, b = 10, c = 15;
Type Inference in Dart
Dart automatically infers the type of variables when var or final is used. This reduces boilerplate code and makes it easier to write clean programs.
var name = 'Dart'; // String
final age = 10; // int
Once inferred, the type cannot be changed:
var name = 'Dart';
name = 10; // ❌ Error
Constants and Immutability
Understanding the difference between final and const is crucial:
| Keyword | When to use | Runtime/Compile-time |
|---|---|---|
| final | Value known at runtime | Runtime |
| const | Value known at compile-time | Compile-time |
Example:
final currentTime = DateTime.now(); // Runtime value
const pi = 3.14159; // Compile-time value
Practical Examples of Variables in Dart
1. Swapping Two Numbers
void main() {
int a = 5, b = 10;
int temp = a;
a = b;
b = temp;
print('a: $a, b: $b'); // a: 10, b: 5
}
2. Using Variables in Functions
void greet(String name) {
print('Hello, $name!');
}
void main() {
String user = 'Ali';
greet(user); // Hello, Ali!
}
3. Calculating Area of Circle
void main() {
const double pi = 3.14159;
double radius = 7;
double area = pi * radius * radius;
print('Area: $area');
}
Best Practices for Variables
- Always use meaningful names →
userAgeis better thanx. - Prefer
finalandconstovervarwhen value shouldn’t change. - Use explicit types in large projects for clarity.
- Avoid dynamic unless necessary → Helps catch errors early.
- Follow camelCase naming convention for readability.
- Keep variable scope as small as possible → Local variables are safer and cleaner.
Common Mistakes
- Changing the type of a variable after inference.
- Forgetting to initialize a
finalvariable. - Using global variables excessively.
- Misunderstanding
constvsfinal. - Ignoring type safety, which can cause runtime errors.
Advanced Variable Features in Dart
Late Variables
Variables declared with late are initialized later, but before usage.
late String name;
void main() {
name = 'Flutter';
print(name);
}
Nullable and Non-Nullable Variables
Dart 2.12+ introduced null safety.
String? nullableName; // Can be null
String nonNullableName = 'Dart'; // Cannot be null
Leave a Reply