Variables and Data Types in Dart – Detailed Notes
Variables and data types are fundamental concepts in Dart programming. They are used to
store, organize, and work with information inside a Dart or Flutter application.
JustAcademy's Flutter curriculum includes Dart Programming Fundamentals, covering
variables, data types, operators, control statements, functions, OOP, collections,
and asynchronous programming. :contentReference[oaicite:0]{index=0}
Learn more about the complete Flutter training:
target="_blank"
rel="noopener noreferrer">
JustAcademy Flutter Training
Register for a course demo:
target="_blank"
rel="noopener noreferrer">
Register for Course Demo
1. What is a Variable?
A variable is a named location used to store a value in a program. The value stored
inside a variable can represent information such as a name, age, price, status,
list of items, or any other data required by an application.
Example:
int age = 25;
In this example:
int is the data type.
age is the variable name.
25 is the value.
= is the assignment operator.
; terminates the statement.
2. Why Are Variables Important?
Variables allow programs to store information and use that information later.
For example, a Flutter application may need to store a user's name, product price,
login status, selected theme, or API response.
String userName = "Rahul";
int userAge = 25;
bool isLoggedIn = true;
print(userName);
print(userAge);
print(isLoggedIn);
Output:
Rahul
25
true
3. Basic Variable Syntax
The general syntax for declaring a typed variable is:
dataType variableName = value;
Example:
String name = "Amit";
int age = 22;
double price = 499.99;
bool active = true;
4. Variable Declaration and Initialization
Declaration means creating a variable, while
initialization means assigning an initial value to it.
int age;
age = 25;
The variable is declared first and then assigned a value.
They can also be combined:
int age = 25;
5. Explicit Data Types
Dart allows developers to explicitly specify the type of data a variable should contain.
int age = 25;
double salary = 45000.50;
String name = "Rahul";
bool isStudent = true;
Explicit typing makes the intended type of a variable clear and helps make code easier
to understand.
6. The var Keyword
Dart supports type inference through the var keyword. When a value is
assigned to a variable declared with var, Dart can infer its type.
var name = "Rahul";
var age = 25;
var price = 99.99;
var isActive = true;
Dart infers:
name as String
age as int
price as double
isActive as bool
7. Difference Between Explicit Type and var
Approach |
Example |
Meaning |
|---|
Explicit type |
int age = 25; |
The type is directly specified. |
Type inference |
var age = 25; |
Dart infers the type from the assigned value. |
8. The dynamic Keyword
The dynamic type allows a variable to hold values of different types.
dynamic value = 100;
value = "Hello";
value = true;
value = 50.5;
Although dynamic is useful in certain situations, it should be used carefully.
Explicit types or inferred static types are generally easier to reason about because they
provide stronger compile-time checking.
9. What Are Data Types?
A data type describes the kind of value that a variable can contain. Data types help
Dart understand how a value should be handled.
Some commonly used Dart data types include:
int
double
num
String
bool
List
Set
Map
Object
dynamic
Null
10. int Data Type
The int type represents whole numbers without decimal values.
int age = 25;
int students = 100;
int score = 95;
Example:
void main() {
int marks = 85;
print(marks);
}
11. double Data Type
The double type represents numbers that can contain decimal values.
double price = 499.99;
double percentage = 85.5;
double temperature = 32.7;
12. num Data Type
The num type can represent both integer and decimal numbers.
num value = 100;
value = 99.50;
This makes num useful when a numeric value may be either an integer or a
floating-point number.
13. String Data Type
The String type is used to store text.
String name = "Rahul";
String city = "Mumbai";
String course = "Flutter Development";
Single Quotes
String name = 'Rahul';
Double Quotes
String name = "Rahul";
String Interpolation
Dart supports string interpolation using the $ symbol.
String name = "Rahul";
int age = 25;
print("My name is $name");
print("My age is $age");
Expressions can be placed inside ${}:
int a = 10;
int b = 20;
print("Total: ${a + b}");
14. bool Data Type
The bool type represents a Boolean value: true or
false.
bool isLoggedIn = true;
bool isAdmin = false;
bool isAvailable = true;
Example:
bool isLoggedIn = true;
if (isLoggedIn) {
print("Welcome");
} else {
print("Please log in");
}
15. List Data Type
A List stores an ordered collection of values. A list can contain multiple
elements and each element has an index.
List fruits = [
"Apple",
"Banana",
"Mango"
];
Accessing an item:
print(fruits[0]);
Output:
Apple
Adding an Item
fruits.add("Orange");
List of Integers
List marks = [80, 85, 90, 95];
16. Set Data Type
A Set is a collection designed to contain unique values.
Set skills = {
"Dart",
"Flutter",
"Firebase"
};
Adding an existing value does not create another duplicate element.
skills.add("Dart");
skills.add("API");
17. Map Data Type
A Map stores data as key-value pairs.
Map user = {
"name": "Rahul",
"age": 25,
"city": "Mumbai"
};
Accessing a value:
print(user["name"]);
print(user["city"]);
Output:
Rahul
Mumbai
18. Object Data Type
Object can represent an instance of any Dart object.
Object value = "Hello";
value = 100;
value = true;
Unlike dynamic, working with an Object value generally requires
appropriate type checks or casting before accessing type-specific members.
19. Null and Nullable Variables
Dart uses null safety. A variable with a non-nullable type normally cannot contain
null.
String name = "Rahul";
To allow a variable to contain null, use ? after the type.
String? middleName;
middleName = null;
Nullable Integer
int? age;
age = null;
age = 25;
20. final Variables
A final variable can be assigned a value only once.
final String name = "Rahul";
print(name);
The variable cannot later be assigned another value.
final int age = 25;
// age = 30; // Error
21. const Variables
A const variable represents a compile-time constant.
const double pi = 3.14159;
const int maxUsers = 100;
22. Difference Between var, final, and const
Keyword |
Can Reassign? |
Example |
|---|
var |
Yes, if the inferred type permits the new value. |
var age = 20; |
final |
No, after the first assignment. |
final age = 20; |
const |
No. |
const age = 20; |
23. Strong Typing in Dart
Dart is a type-safe language. When a variable is declared with a particular type,
assigning an incompatible value generally produces a compile-time error.
int age = 25;
// age = "Twenty-five"; // Invalid
The variable age is an integer and cannot simply be assigned a string.
24. Type Inference
Dart can automatically determine a variable's type from its initial value.
var name = "Rahul";
var age = 25;
var price = 499.99;
The compiler can infer the types from these values.
25. Generic Collections
Dart allows collections to specify the type of elements they contain. This is called
using generics.
List names = [
"Rahul",
"Amit",
"Priya"
];
List numbers = [
10,
20,
30
];
Maps can also specify key and value types:
Map scores = {
"Rahul": 90,
"Amit": 85,
"Priya": 95
};
26. Type Checking with is
Dart provides the is operator to check whether a value is of a particular type.
dynamic value = "Hello";
if (value is String) {
print("Value is a String");
}
27. Type Casting
When working with a value whose static type is broader than the type you need, Dart provides
type casting using the as operator.
Object value = "Hello";
String text = value as String;
print(text.length);
Casting should be used only when the programmer knows that the value has the expected type.
28. Common Variable Naming Practices
Meaningful variable names make code easier to understand.
Good Examples
String firstName = "Rahul";
int totalMarks = 450;
double productPrice = 999.99;
bool isLoggedIn = true;
Less Descriptive Examples
String x = "Rahul";
int a = 450;
double p = 999.99;
Short names can be appropriate in small contexts, but descriptive names are generally
easier to maintain in application code.
29. Multiple Variables
Dart allows several variables to be declared separately for clarity.
String name = "Rahul";
int age = 25;
String city = "Mumbai";
print(name);
print(age);
print(city);
30. Updating Variable Values
Variables declared with var or explicit mutable types can be reassigned.
int age = 20;
print(age);
age = 21;
print(age);
Output:
20
21
31. Variables Inside Functions
Variables can be declared inside functions and used within their appropriate scope.
void calculateTotal() {
int price = 500;
int quantity = 2;
int total = price * quantity;
print(total);
}
void main() {
calculateTotal();
}
32. Variables as Function Parameters
Functions can receive values through parameters.
void greetUser(String name) {
print("Hello $name");
}
void main() {
greetUser("Rahul");
}
33. Variables and Flutter
Variables and data types are used throughout Flutter development. JustAcademy's Flutter
curriculum specifically lists variables and data types as part of Dart Programming
Fundamentals, alongside functions, OOP, collections, and asynchronous programming.
:contentReference[oaicite:1]{index=1}
For example, a Flutter widget may contain variables like:
class Product {
String name;
double price;
bool isAvailable;
Product({
required this.name,
required this.price,
required this.isAvailable,
});
}
Here:
name uses the String type.
price uses the double type.
isAvailable uses the bool type.
34. Complete Example: Variables and Data Types
void main() {
// Basic data types
String name = "Rahul";
int age = 25;
double salary = 45000.50;
bool isEmployee = true;
// Collection data types
List skills = [
"Dart",
"Flutter",
"Firebase"
];
Set technologies = {
"Flutter",
"Dart",
"Firebase"
};
Map user = {
"name": name,
"age": age,
"employee": isEmployee
};
// Display values
print("Name: $name");
print("Age: $age");
print("Salary: $salary");
print("Employee: $isEmployee");
print("Skills: $skills");
print("Technologies: $technologies");
print("User: $user");
}
35. Summary of Dart Data Types
Data Type |
Purpose |
Example |
|---|
int |
Whole numbers |
int age = 25; |
double |
Decimal numbers |
double price = 99.99; |
num |
Integer or decimal numbers |
num value = 10.5; |
String |
Text |
String name = "Rahul"; |
bool |
True or false |
bool active = true; |
List |
Ordered collection |
List numbers = [1, 2, 3]; |
Set |
Unique collection |
Set names = {"A", "B"}; |
Map |
Key-value collection |
Map scores = {}; |
Object |
General Dart object type |
Object value = "Hello"; |
dynamic |
Dynamic type |
dynamic value = 100; |
Null |
Represents the null value |
String? name; |
36. Common Beginner Mistakes
Using an Incorrect Type
int age = "25";
This is invalid because "25" is a string rather than an integer.
Correct Version
int age = 25;
Trying to Reassign a final Variable
final int age = 25;
// age = 30; // Error
Using Null with a Non-Nullable Variable
// String name = null; // Invalid
String? name = null; // Valid
Unnecessary Use of dynamic
dynamic age = 25;
If the value is known to be an integer, using int communicates the intended
type more clearly:
int age = 25;
37. Best Practices
- Use meaningful variable names.
- Use explicit types when they improve clarity.
- Use
var when type inference keeps the code clear.
- Prefer
final for values that should not be reassigned.
- Use
const for compile-time constants.
- Use nullable types only when a value can legitimately be absent.
- Use typed collections such as
List and Map.
- Avoid unnecessary use of
dynamic.
- Keep variables within an appropriate scope.
- Choose data types according to the actual information being stored.
38. Practice Exercises
- Create a variable containing your name using
String.
- Create an integer variable containing your age.
- Create a
double variable containing a product price.
- Create a Boolean variable representing login status.
- Create a List containing five programming languages.
- Create a Set containing three unique skills.
- Create a Map containing a user's name, age, and city.
- Create a nullable String variable.
- Write an example using
var.
- Write examples demonstrating
final and const.
- Create a function that accepts a String and an int as parameters.
- Create a small Flutter model class using String, int, double, and bool properties.
39. Quick Revision
- Variable: A named storage location for a value.
- Data type: Defines the kind of value a variable represents.
- int: Whole numbers.
- double: Decimal numbers.
- num: Numeric values that can be integers or doubles.
- String: Text values.
- bool:
true or false.
- List: Ordered collection.
- Set: Collection of unique values.
- Map: Key-value collection.
- var: Allows Dart to infer the variable's type.
- dynamic: Allows dynamic typing.
- final: Value can be assigned only once.
- const: Compile-time constant.
- ? Makes a type nullable.
40. Conclusion
Variables and data types are essential building blocks of Dart programming. Understanding
how to declare variables, use explicit types, apply type inference, work with collections,
handle nullable values, and use final and const provides a strong
foundation for Flutter development.
JustAcademy's Flutter training includes variables and data types as part of its Dart
Programming Fundamentals module, followed by topics such as operators, control statements,
functions, OOP, collections, and asynchronous programming. :contentReference[oaicite:2]{index=2}
Useful JustAcademy Links
Flutter Training:
target="_blank"
rel="noopener noreferrer">
JustAcademy Flutter Training
Course Demo:
target="_blank"
rel="noopener noreferrer">
Register for Course Demo