Fetching latest headlines…
How to Declare Variables in Dart ?
NORTH AMERICA
🇺🇸 United StatesJuly 3, 2026

How to Declare Variables in Dart ?

0 views0 likes0 comments
Originally published byDev.to

💙 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 var when the type is obvious.
  • ⚠️ Use dynamic only 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

Comments (0)

Sign in to join the discussion

Be the first to comment!