๐ Dart Basics: How to Declare Variables in Dart
Variables are used to store data in a program. Every Flutter developer works with variables every day, so understanding them is an important first step in learning Dart.
๐ 1. Declare a Variable with a Data Type
When you already know the type of data, declare it explicitly.
String name = "Tuhin";
int age = 22;
double height = 5.8;
bool isStudent = true;
โ This makes your code easier to read and maintain.
๐ 2. Using var
The var keyword tells Dart to automatically detect the variable's type from the first value you assign.
var city = "Dhaka";
var year = 2025;
print(city);
print(year);
Once the type is assigned, it cannot be changed.
var city = "Dhaka";
city = "Rajshahi"; // โ
Correct
// city = 100; // โ Error
๐ 3. Using dynamic
The dynamic keyword allows a variable to hold values of different data types.
dynamic data = "Hello";
print(data);
data = 100;
print(data);
Another example:
dynamic value = true;
value = 3.14;
value = "Flutter";
This works because dynamic does not enforce a fixed data type.
๐ var vs dynamic
| Feature | var |
dynamic |
|---|---|---|
| Type Inference | โ Yes | โ No fixed type |
| Type Changes | โ Not Allowed | โ Allowed |
| Type Safety | โ Strong | โ Weak |
| Performance | โ Better | โ ๏ธ Slightly less efficient |
| Best Use | When the type is known | When different types are required |
๐ก Best Practice
- โ Use explicit data types for better readability.
- โ
Use
varwhen the type is obvious. - โ ๏ธ Use
dynamiconly when you really need to store different types of values.
Choosing the right variable type helps you write cleaner, safer, and more maintainable Dart code.
๐ฌ Which one do you use most in your Flutter projectsโvar or dynamic?
Flutter #Dart #FlutterDeveloper #Programming #MobileDevelopment #SoftwareEngineering
United States
NORTH AMERICA
Related News
Secret Claude Tracker Shocks Users After Anthropic's Anti-Surveillance Stance
12h ago
EV Batteries Defy Expectations, Last Hundreds of Thousands of Miles
1d ago
GBase 8a Performance Anomaly Case Study: How a Single Parameter Change Sparked a Chain Reaction
1d ago
Who Else Has Inherited a Codebase With Zero Comments and a Prayer?
1d ago
ๅฎ็พ็ๅนณๅบธ
4h ago