Popular Searches
Popular Course Categories
Popular Courses

Dart Variables and Constants

Dart Variables and Constants

5 mins Dart Basics

Dart Variables and Constants – Detailed Notes

Variables and constants are fundamental concepts in Dart programming. They are used to store values such as names, numbers, prices, user information, application settings, and other 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}

Dart is the programming language used with Flutter to build applications from a shared codebase for platforms such as Android and iOS. :contentReference[oaicite:1]{index=1}


1. What is a Variable?

A variable is a named storage location used to hold a value in a Dart program. The value stored in a variable can generally be changed during program execution.

For example:

String name = "Rahul";
int age = 25;

print(name);
print(age);

Here, name stores a String value and age stores an integer value.

Basic Variable Structure

dataType variableName = value;

Example:

int marks = 85;
String city = "Mumbai";
double price = 499.99;
bool isActive = true;

2. Declaring and Initializing Variables

Declaration means creating a variable, while initialization means assigning a value to it.

int age;

The variable is declared but no value has been assigned yet.

age = 25;

Now the variable has been initialized.

You can also declare and initialize a variable in one statement:

int age = 25;

3. Explicitly Typed Variables

Dart allows you to explicitly specify the data type of a variable.

String studentName = "Amit";
int studentAge = 22;
double percentage = 87.5;
bool passed = true;

Explicit typing makes the intended type of the data clear and helps prevent accidental assignment of incompatible values.

Example

int quantity = 10;

// quantity = "Ten"; // Error

Because quantity is declared as an int, it should contain an integer value.


4. Using var

Dart provides the var keyword for type inference. Dart determines the variable's type from the value assigned to it.

var name = "Rahul";
var age = 25;
var price = 199.99;
var isLoggedIn = true;

Dart infers the types as String, int, double, and bool respectively.

Important Point

var does not mean that the variable can freely change from one type to another.

var age = 25;

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

Once Dart infers the type, assigning an incompatible type is not allowed.


5. Using dynamic

The dynamic type allows a variable to hold values of different types.

dynamic value = 100;

print(value);

value = "Hello Dart";

print(value);

value = true;

print(value);

Although dynamic is flexible, it should be used carefully because it reduces some of the type-safety benefits of Dart.

var vs dynamic

Feature var dynamic
Type inference Yes No fixed type at compile time
Type can change No Yes
Type safety Higher Lower
Recommended usage Common When dynamic behavior is genuinely required

6. Changing the Value of a Variable

A normal variable can be assigned a new value as long as the new value is compatible with its type.

int score = 50;

print(score);

score = 75;

print(score);

score = 90;

print(score);

Output:

50
75
90

7. What is a Constant?

A constant is a value that should not be reassigned after it has been initialized.

Dart provides two important keywords for values that should not be reassigned:

  • final
  • const

Although both prevent reassignment, they have different purposes.


8. The final Keyword

A final variable can be assigned only once. Its value can be determined at runtime.

final String name = "Rahul";

print(name);

This is not allowed:

final String name = "Rahul";

// name = "Amit"; // Error

Runtime Value with final

A final variable can receive a value calculated or obtained while the program is running.

final currentTime = DateTime.now();

print(currentTime);

The value of currentTime is determined when the program executes.


9. The const Keyword

The const keyword is used for compile-time constants. The value must be known at compile time.

const double pi = 3.14159;
const int maxUsers = 100;

print(pi);
print(maxUsers);

A const variable cannot be reassigned.

const int maxScore = 100;

// maxScore = 200; // Error

10. final vs const

Feature final const
Assignment Only once Only once
Value determined Can be determined at runtime Must be known at compile time
Can change after assignment? No No
Example final date = DateTime.now(); const pi = 3.14159;
Typical use Values assigned once during execution Compile-time constant values

Simple Way to Remember

final = assigned once

const = compile-time constant

11. Examples of final and const

Example 1 – final

final username = "Amit";

print(username);

Example 2 – const

const appName = "My Flutter App";

print(appName);

Example 3 – Runtime Value

final loginTime = DateTime.now();

print(loginTime);

Example 4 – Compile-Time Value

const maxLoginAttempts = 3;

print(maxLoginAttempts);

12. Variable Naming Rules in Dart

Dart variable names should follow valid identifier rules.

Valid Examples

String firstName = "Rahul";
int userAge = 25;
double productPrice = 499.50;
bool isLoggedIn = true;

Invalid Examples

// int 123age = 25;
// String user-name = "Rahul";
// double product price = 100.0;

Spaces, hyphens in ordinary identifiers, and identifiers beginning with numbers are not valid in these examples.


13. Recommended Naming Convention

Dart commonly uses lowerCamelCase for variable and constant identifiers.

String firstName = "Rahul";
String emailAddress = "[email protected]";
int totalProducts = 50;
double totalPrice = 1250.50;
bool isAvailable = true;

Prefer meaningful names:

// Good
double productPrice = 999.99;

// Less descriptive
double x = 999.99;

14. Variables with Different Data Types

String studentName = "Priya";
int studentAge = 21;
double studentPercentage = 88.75;
bool isPassed = true;

print(studentName);
print(studentAge);
print(studentPercentage);
print(isPassed);

These variables demonstrate some of the common data types used in Dart programming.


15. Multiple Variables

Dart allows multiple variables to be declared in a program.

String name = "Amit";
int age = 24;
String city = "Mumbai";
double salary = 45000.0;
bool isEmployee = true;

16. Variables Inside Functions

Variables can be declared inside functions. Such variables are generally local to that function.

void showStudent() {
  String name = "Rahul";
  int age = 22;

  print(name);
  print(age);
}

void main() {
  showStudent();
}

17. Global Variables

A variable declared outside a function or class can have a broader scope depending on how the program is structured.

String appName = "Student App";

void main() {
  print(appName);
}

In larger Flutter applications, it is important to manage shared values carefully and avoid unnecessary global mutable state.


18. Nullable Variables

Dart uses null safety. If a variable is not intended to contain null, its type normally cannot contain null.

String name = "Rahul";

// name = null; // Error

To allow a variable to contain null, use the ? symbol.

String? middleName;

middleName = null;

print(middleName);

Here, String? means the variable can contain either a String value or null.


19. final with Nullable Variables

final String? nickname = null;

print(nickname);

The variable cannot be reassigned, but its type allows the value to be null.


20. const Collections

Dart also allows compile-time constant collections when their contents are compile-time constants.

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

print(cities);

A constant collection cannot be modified.

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

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

21. final List vs const List

One important difference is that final prevents reassignment of the variable, while the list itself can still be mutable unless it is otherwise made unmodifiable.

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

cities.add("Pune");

print(cities);

The variable cities cannot be assigned to a different list, but the existing list can be modified.

With const:

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

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

The constant list cannot be modified.


22. Variable vs final vs const

Declaration Can Reassign? Runtime Value? Compile-Time Constant?
var Yes Yes No
Explicit type Yes Yes No
final No Yes Not necessarily
const No No Yes

23. Practical Example – Student Information

void main() {
  String studentName = "Rahul";
  int age = 21;
  double marks = 87.5;
  bool passed = true;

  final studentId = "ST101";
  const instituteName = "JustAcademy";

  print("Student Name: $studentName");
  print("Age: $age");
  print("Marks: $marks");
  print("Passed: $passed");
  print("Student ID: $studentId");
  print("Institute: $instituteName");
}

Explanation

  • studentName is a String variable.
  • age is an integer variable.
  • marks is a double variable.
  • passed is a Boolean variable.
  • studentId is assigned once using final.
  • instituteName is a compile-time constant using const.

24. Practical Example – E-Commerce Application

void main() {
  String productName = "Laptop";
  double productPrice = 65000.0;
  int quantity = 2;

  final orderId = "ORD1001";
  const taxRate = 0.18;

  double subtotal = productPrice * quantity;
  double tax = subtotal * taxRate;
  double total = subtotal + tax;

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

This example demonstrates how normal variables, final, and const can be used together in an application.


25. Variables in Flutter Applications

Dart variables are used throughout Flutter applications to store application data, UI state, user input, configuration values, API responses, and other information. JustAcademy's Flutter curriculum specifically includes Dart fundamentals such as variables, data types, operators, functions, OOP, collections, and asynchronous programming. :contentReference[oaicite:2]{index=2}

Example

String userName = "Rahul";
int notificationCount = 5;
bool isDarkMode = false;

print(userName);
print(notificationCount);
print(isDarkMode);

In a Flutter application, these types of values can be used to control what is displayed on the screen or how an application behaves.


26. Constants in Flutter

Constants can be useful for values that should remain fixed throughout an application or for compile-time constant configuration.

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

Flutter code also commonly uses compile-time constants with the const keyword where appropriate.


27. 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 – Using null with a Non-Nullable Variable

String name = "Rahul";

// name = null; // Error

Use a nullable type when null is expected:

String? name = null;

Mistake 4 – Using dynamic Everywhere

dynamic data = "Hello";
data = 100;
data = true;

Although this is valid, excessive use of dynamic can make code harder to understand and reduce the benefits of static type checking.


28. Best Practices for Dart Variables and Constants

  • Use meaningful variable names.
  • Use lowerCamelCase for variable names.
  • Use final when a value should be assigned only once.
  • Use const when a value is a compile-time constant.
  • Prefer clear static types or type inference instead of unnecessary dynamic.
  • Use nullable types only when a value can genuinely be null.
  • Avoid unnecessary global mutable variables.
  • Keep application configuration values centralized when appropriate.
  • Use constants for repeated fixed values where suitable.
  • Choose the simplest declaration that clearly communicates your intent.

29. Quick Revision

Concept Meaning Example
Variable Stores a value that can generally be changed int age = 25;
var Uses type inference var name = "Rahul";
dynamic Allows values of different types dynamic value = 10;
final Can be assigned only once final id = "101";
const Compile-time constant const pi = 3.14;
Nullable variable Can contain null String? name;

30. Practice Exercises

  1. Create a String variable containing your name.
  2. Create an integer variable containing your age.
  3. Create a double variable containing a product price.
  4. Create a Boolean variable called isStudent.
  5. Create a final variable containing a student ID.
  6. Create a const variable containing the maximum number of users.
  7. Create a nullable String variable.
  8. Create a List using final and add an item to it.
  9. Create a constant List and try to modify it.
  10. Write a small Dart program using variables, final, and const together.

31. Complete Example

void main() {
  // Normal variables
  String name = "Amit";
  int age = 25;
  double salary = 45000.50;
  bool isDeveloper = true;

  // Type inference
  var city = "Mumbai";

  // Assigned once
  final employeeId = "EMP101";

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

  // Nullable variable
  String? nickname;

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

32. Key Takeaways

  • A variable is used to store data in a Dart program.
  • Variables can be declared using an explicit type or var.
  • var uses type inference.
  • dynamic allows values of different types but should be used carefully.
  • final means a variable can be assigned only once.
  • const represents a compile-time constant.
  • String?, int?, and similar nullable types can contain null.
  • Meaningful variable names improve code readability.
  • Variables and constants are fundamental parts of Dart programming and therefore important for Flutter development.

Learn Flutter with JustAcademy

JustAcademy's Flutter training covers Dart programming fundamentals, including variables, data types, operators, functions, OOP, collections, and asynchronous programming, along with practical Flutter development. :contentReference[oaicite:3]{index=3}

Learn more through the official JustAcademy Flutter Training Course .

You can also register for a course demonstration through the JustAcademy Course Demo Registration .

These concepts provide an important foundation for progressing from Dart fundamentals into Flutter widgets, application structure, state management, API integration, and real-world mobile application development. :contentReference[oaicite:4]{index=4}

whatsapp