DEV Community

M R Tuhin
M R Tuhin

Posted on

πŸ’™ Dart Basics: How to Declare Variables in Dart ?

Variables are used to store data in a program. In Dart, there are multiple ways to declare a variable depending on your requirements.

Let's explore the most common ways.


πŸ“Œ 1. Declare Variables with Explicit Data Types

Use the data type when you know exactly what kind of value the variable will store.

String name = "Tuhin";
int age = 25;
double height = 5.8;
bool isFlutterDeveloper = true;
Enter fullscreen mode Exit fullscreen mode

βœ… This approach makes your code more readable and type-safe.


πŸ“Œ 2. Declare Variables with var

The var keyword lets Dart automatically determine the variable's type.

var city = "Dhaka";
var year = 2026;
Enter fullscreen mode Exit fullscreen mode

After the first value is assigned, the variable's type cannot change.

var city = "Dhaka";

city = "Khulna";   // βœ… Valid
// city = 100;      // ❌ Error
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 3. Declare Variables with dynamic

Use dynamic when a variable may store different types of values.

dynamic value = "Flutter";
value = 100;
value = true;
Enter fullscreen mode Exit fullscreen mode

The variable can change its type during program execution.


πŸ“Œ 4. Declare Variables with final

A final variable can be assigned only once.

final String country = "Bangladesh";
final currentYear = 2026;
Enter fullscreen mode Exit fullscreen mode

Once a value is assigned, it cannot be changed.


πŸ“Œ 5. Declare Variables with const

Use const for values that are known at compile time and will never change.

const double pi = 3.14159;
const appName = "Flutter Learning";
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Best Practice

  • βœ… Use explicit data types when the type should be clear.
  • βœ… Use var when the type is obvious from the assigned value.
  • βœ… Use final for values that should not change after initialization.
  • βœ… Use const for compile-time constant values.
  • ⚠️ Use dynamic only when different data types are truly required.

Writing variables correctly is one of the first steps toward writing clean, maintainable, and professional Dart code.

πŸ’¬ Which way do you prefer to declare variables in Dart?

Flutter #Dart #FlutterDeveloper #Programming #MobileDevelopment #SoftwareEngineering #CleanCode #DeveloperCommunity #LearnToCode

Top comments (0)