Popular Searches
Popular Course Categories
Popular Courses

var, final, const, and variable declaration

var, final, const, and variable declaration

5 mins Dart Basics

Dart: var, final, const, and Variable Declaration

Variables are one of the most important foundations of Dart programming. They allow developers to store and work with values such as names, numbers, prices, user information, application settings, and API data. JustAcademy's Flutter curriculum includes Dart programming fundamentals such as variables, data types, and operators as part of its Flutter training. :contentReference[oaicite:0]{index=0}

Understanding var, final, const, and explicit variable declarations is especially important before moving into Flutter widgets, state management, API integration, and other application-development topics.


1. What is a Variable in Dart?

A variable is a named location used to store a value in a Dart program. A variable has a name and a type, either explicitly declared or inferred by Dart.

For example:

String name = "Rahul";
int age = 25;
double price = 499.99;
bool isActive = true;

Here:

  • name stores a String.
  • age stores an integer.
  • price stores a decimal number.
  • isActive stores a Boolean value.

2. Basic Variable Declaration Syntax

The general syntax for explicitly declaring a variable is:

dataType variableName = value;

Example:

String studentName = "Amit";
int studentAge = 21;
double percentage = 85.5;
bool passed = true;

Breaking Down the Syntax

int age = 25;
  • int → data type
  • age → variable name
  • = → assignment operator
  • 25 → value
  • ; → statement terminator

3. Declaring a Variable Without an Initial Value

A variable can be declared first and assigned a value later when the declaration permits it.

int age;

age = 25;

print(age);

This approach can be useful when a value will be determined later in the program.

Example

String message;

message = "Welcome to Dart";

print(message);

4. Declaring and Initializing in One Statement

The most common approach is to declare and initialize a variable at the same time.

String name = "Rahul";
int age = 24;
double salary = 45000.50;

This makes the variable's intended value immediately clear.


5. Using var in Dart

The var keyword allows Dart to determine the variable's type automatically from the value assigned to it. This is called type inference.

var name = "Rahul";
var age = 25;
var price = 999.99;
var isStudent = true;

Dart infers:

  • name → String
  • age → int
  • price → double
  • isStudent → bool

JustAcademy's Dart interview material similarly describes var as type inference: after a value is assigned, Dart determines the variable's type. :contentReference[oaicite:1]{index=1}


6. Example of var

void main() {
  var name = "Amit";
  var age = 22;
  var marks = 87.5;

  print(name);
  print(age);
  print(marks);
}

Output:

Amit
22
87.5

7. Can a var Variable Change?

Yes, a var variable can be assigned a new value, but the new value must be compatible with its inferred type.

var age = 25;

age = 30;

print(age);

This is valid because both values are integers.

However:

var age = 25;

// age = "Twenty Five"; // Error

Dart inferred age as an int, so assigning a String is not valid.


8. var vs Explicit Data Type

Both of these declarations are valid:

String name = "Rahul";

var name = "Rahul";

In the first example, the developer explicitly specifies the type. In the second example, Dart infers the type.

Feature Explicit Type var
Type written by developer Yes No
Type inferred by Dart Not necessary Yes
Can value be reassigned? Yes, if type-compatible Yes, if type-compatible
Example int age = 25; var age = 25;

9. What is final?

The final keyword is used when a variable should be assigned only once.

final String name = "Rahul";

print(name);

Once a value has been assigned to a final variable, the variable cannot be reassigned.

final age = 25;

// age = 30; // Error

10. final Values Can Be Determined at Runtime

One important characteristic of final is that the value does not have to be known when the program is compiled. It can be determined during program execution.

final currentTime = DateTime.now();

print(currentTime);

DateTime.now() produces a value when the program runs, so final is appropriate here.


11. Practical Uses of final

Examples include:

final userId = "USER101";
final loginTime = DateTime.now();
final username = "Amit";
final totalPrice = 1500.0;

These values may be assigned during application execution but should not be reassigned afterward.


12. What is const?

The const keyword is used to create a compile-time constant.

const pi = 3.14159;
const maxUsers = 100;
const appName = "My App";

The values of these constants must be available at compile time.


13. Example of const

void main() {
  const appName = "Student App";
  const maxStudents = 100;

  print(appName);
  print(maxStudents);
}

Output:

Student App
100

14. const Cannot Be Reassigned

const pi = 3.14159;

// pi = 3.14; // Error

A constant is fixed and cannot be reassigned.


15. final vs const

The difference between final and const is one of the most important concepts in Dart. JustAcademy's Dart interview material describes final as a value that is assigned once and may be determined at runtime, while const is used for compile-time constant values. :contentReference[oaicite:2]{index=2}

Feature final const
Can be assigned only once? Yes Yes
Can value be determined at runtime? Yes No
Compile-time constant? Not necessarily Yes
Example final time = DateTime.now(); const pi = 3.14159;

Easy Way to Remember

final → assigned once

const → compile-time constant

16. var vs final vs const

Keyword Reassignment Type Inference Runtime Value Compile-Time Constant
var Allowed Yes Yes No
final Not allowed Yes Yes Not necessarily
const Not allowed Yes No Yes

17. Explicit Variable Declaration

Instead of using var, you can explicitly specify the type of a variable.

String name = "Rahul";
int age = 25;
double salary = 50000.50;
bool isEmployee = true;

Explicit declarations are useful when you want the type to be immediately visible to someone reading the code.


18. Variable Declaration with List

List names = [
  "Amit",
  "Rahul",
  "Priya"
];

Using var:

var names = [
  "Amit",
  "Rahul",
  "Priya"
];

Dart can infer the list's element type from the values.


19. Variable Declaration with Map

Map student = {
  "name": "Rahul",
  "age": 21,
  "passed": true
};

Using var:

var student = {
  "name": "Rahul",
  "age": 21,
  "passed": true
};

20. final with Collections

A final collection variable cannot be reassigned to another collection, but the collection itself can generally still be modified.

final List cities = [
  "Mumbai",
  "Delhi"
];

cities.add("Pune");

print(cities);

The list can be modified, but the variable cannot point to a completely different list.

final cities = ["Mumbai", "Delhi"];

// cities = ["Pune", "Nashik"]; // Error

21. const with Collections

A const collection is a compile-time constant collection and cannot be modified.

const cities = [
  "Mumbai",
  "Delhi",
  "Pune"
];

Trying to modify it is invalid:

// cities.add("Nashik"); // Error

22. Variable Declaration and Null Safety

Dart's null-safety system distinguishes between variables that can contain null and variables that cannot.

Non-nullable variable:

String name = "Rahul";

Nullable variable:

String? name;

name = null;

The ? indicates that the variable may contain either a String or null.


23. Multiple Variable Declarations

Multiple variables can be declared individually for readability.

String firstName = "Rahul";
String lastName = "Sharma";
int age = 25;
String city = "Mumbai";

In most production code, clear individual declarations are preferable when variables represent different concepts.


24. Local Variables

A variable declared inside a function or block is generally a local variable.

void showUser() {
  String name = "Amit";
  int age = 25;

  print(name);
  print(age);
}

void main() {
  showUser();
}

The variables name and age are local to the function.


25. Variables as Function Parameters

Variables can also be received as parameters by functions.

void greetUser(String name) {
  print("Hello $name");
}

void main() {
  greetUser("Rahul");
}

Here, name is a parameter that receives a value when the function is called.


26. Practical Example – Student Application

void main() {
  var studentName = "Amit";
  var age = 21;
  var marks = 87.5;

  final studentId = "ST101";

  const instituteName = "JustAcademy";
  const passingMarks = 40;

  print("Student: $studentName");
  print("Age: $age");
  print("Marks: $marks");
  print("Student ID: $studentId");
  print("Institute: $instituteName");
  print("Passing Marks: $passingMarks");
}

Concepts Used

  • var is used for inferred variables.
  • final is used for a value assigned once.
  • const is used for compile-time constant values.
  • String interpolation is used to display variable values.

27. Practical Example – Flutter App Configuration

const String appName = "My Flutter App";
const int maxItems = 20;
const double defaultPadding = 16.0;

final String sessionId = "SESSION101";

var username = "Rahul";
var notificationCount = 5;

In a Flutter application, constants can be useful for fixed configuration values, while final can be useful for values that are determined once during execution. Flutter development in the JustAcademy curriculum builds on Dart fundamentals before moving into widgets, navigation, state management, APIs, Firebase, and other application topics. :contentReference[oaicite:3]{index=3}


28. Practical Example – E-Commerce Application

void main() {
  var productName = "Laptop";
  var quantity = 2;
  var price = 65000.0;

  final orderId = "ORD1001";

  const taxRate = 0.18;

  var subtotal = price * quantity;
  var tax = subtotal * taxRate;
  var total = subtotal + tax;

  print("Product: $productName");
  print("Quantity: $quantity");
  print("Order ID: $orderId");
  print("Subtotal: $subtotal");
  print("Tax: $tax");
  print("Total: $total");
}

29. Common Mistakes

Mistake 1 – Reassigning a final Variable

final age = 25;

// age = 30; // Error

Mistake 2 – Reassigning a const Variable

const pi = 3.14;

// pi = 3.14159; // Error

Mistake 3 – Assigning the Wrong Type to var

var age = 25;

// age = "25"; // Error

Mistake 4 – Confusing final with const

final currentTime = DateTime.now();

const pi = 3.14159;

The first value is obtained during execution, while the second is a compile-time constant.

Mistake 5 – Using dynamic Unnecessarily

dynamic value = "Hello";

value = 100;
value = true;

dynamic is flexible, but normal variables with appropriate static types are usually clearer when the data type is known.


30. Best Practices

  • Use meaningful and descriptive variable names.
  • Use var when type inference makes the code clear.
  • Use explicit types when they improve readability or communicate an important contract.
  • Use final when a variable should not be reassigned after initialization.
  • Use const for compile-time constants.
  • Avoid unnecessary use of dynamic.
  • Use nullable types such as String? only when null is a valid value.
  • Use lowerCamelCase for ordinary Dart variable names.
  • Keep fixed configuration values centralized where appropriate.
  • Choose declarations that make the intent of the code easy to understand.

31. Quick Comparison

Declaration Example Can Reassign? Type Inferred? Main Purpose
Explicit type int age = 25; Yes No Clearly specify the type
var var age = 25; Yes Yes Type inference
final final age = 25; No Yes Assign once
const const age = 25; No Yes Compile-time constant

32. Easy Memory Trick

var
↓
Value can change
Type is inferred

final
↓
Value is assigned once
Can be determined at runtime

const
↓
Compile-time constant
Cannot be reassigned

33. Practice Questions

  1. What is a variable in Dart?
  2. What is the syntax for declaring a variable with an explicit type?
  3. What is type inference?
  4. How does var work in Dart?
  5. Can a var variable be reassigned?
  6. What is the purpose of final?
  7. Can a final variable receive a runtime value?
  8. What is a compile-time constant?
  9. What is the difference between final and const?
  10. Can a constant variable be reassigned?
  11. What happens when a var variable is initialized with an integer?
  12. How do you declare a nullable variable?
  13. What is the difference between an explicit type and var?
  14. When should you use final?
  15. When should you use const?

34. Practice Coding Exercises

  1. Create a variable called name using var.
  2. Create an integer variable called age using an explicit type.
  3. Create a final variable called userId.
  4. Create a const variable called maxScore.
  5. Create a final variable using DateTime.now().
  6. Create a constant String containing an application name.
  7. Create a List using final and add a new item.
  8. Create a constant List and observe what happens when you try to modify it.
  9. Create a nullable String variable.
  10. Build a small Dart program using var, final, and const together.

35. Complete Dart Example

void main() {
  // Explicit variable declaration
  String name = "Rahul";
  int age = 25;

  // Type inference using var
  var city = "Mumbai";
  var salary = 50000.0;

  // Value assigned only once
  final employeeId = "EMP101";

  // Compile-time constants
  const companyName = "Tech Solutions";
  const workingHours = 8;

  // Nullable variable
  String? nickname;

  // Reassignable variables
  age = 26;
  city = "Pune";

  print("Name: $name");
  print("Age: $age");
  print("City: $city");
  print("Salary: $salary");
  print("Employee ID: $employeeId");
  print("Company: $companyName");
  print("Working Hours: $workingHours");
  print("Nickname: $nickname");
}

36. Key Takeaways

  • A variable stores data that can be used by a Dart program.
  • Variables can be declared using an explicit data type.
  • var lets Dart infer the variable's type.
  • A var variable can be reassigned with a compatible value.
  • final allows a variable to be assigned only once.
  • A final value can be determined at runtime.
  • const is used for compile-time constant values.
  • final and const variables cannot be reassigned.
  • Use meaningful names and appropriate types to make Dart code readable.
  • These concepts form part of the Dart programming fundamentals used in Flutter development. :contentReference[oaicite:4]{index=4}

Learn Flutter with JustAcademy

JustAcademy's Flutter training includes Dart programming fundamentals such as variables, data types, operators, functions, OOP, collections, and asynchronous programming, followed by practical Flutter development topics. :contentReference[oaicite:5]{index=5}

Explore the course: JustAcademy Flutter Training

Register for a course demo: JustAcademy Course Demo Registration

Learning var, explicit variable declarations, final, and const provides a strong foundation for writing clean Dart code and progressing toward Flutter application development.

whatsapp