If you are starting your journey as a Flutter developer, the first thing you must learn about variables and data types in Dart. By the end, you will clearly understand how to use variables in Dart programming.

What is a Variable in Dart?

Variable is like a container that stores a value. You can use that value later in your program.

In Dart, variables can be declared using var, final, const. And directly declared data type like int, double, String.

Data Types in Dart with Examples

  • Integer (int) Stores whole numbers.
void main() {
  int age = 25;
  int year = 2025;
  print("Age: $age");
  print("Year: $year");
}
  • Double (double) Stores decimal numbers.
void main() {
  double price = 99.99;
  double pi = 3.1416;
  print("Price: $price");
  print("PI: $pi");
}
  • String (String) Stores simple text.
void main() {
String name = "Shafiq";
String city = "Dhaka";
print("My name is $name");
print("I live in $city");
}
  • Boolean (bool) Stores true/false values.
void main() {
bool isFlutterEasy = true;
bool isDartHard = false;
print("Flutter easy? $isFlutterEasy");
print("Dart hard? $isDartHard");
}
  • List (List) Stores multiple values.
void main() {
List<String> fruits = ["Apple", "Banana", "Mango"];
print(fruits);
print("First fruit: ${fruits[0]}");
}
  • Map (Map) Stores key-value pairs.
void main() {
Map<String, String> capitals = {
"Bangladesh": "Dhaka",
"Pakistan": "Islamabad",
"India": "New Delhi",
"USA": "Washington DC"
};

print(capitals);
print("Capital of Bangladesh: ${capitals["Bangladesh"]}");
}

var, final, and const in Dart

  •  Can change later
var city = "Dhaka";
  • Allowed for changing the value
city = "Chittagong";
  • Cannot change later
final country = "Bangladesh";
  • Not allowed to change the value
country = "India";
  • Fixed at compile-time
const pi = 3.14;
  • Not allowed to change
pi = 3.1416;

Best Practices

Use descriptive variable names. Utilize final and const whenever possible. Choose the appropriate data type for efficiency.

FAQs about Dart Variables and Data Types

Q1: What is a variable in Dart?

A variable is a named container that stores multiple type of values like a number, text, or boolean.

Q2: What are the main data types in Dart?

The main data types are int, double, String, bool, List, and Map.

Q3: What is the difference between var, final, and const in Dart?
  • The var value can change later.
  • The final value cannot change once assigned.
  • The const value is constant at compile time.

Final Thoughts

Gaining a solid understanding of variables and data types in Dart is essential for anyone aspiring to become a Flutter developer. By mastering integers, doubles, strings, booleans, lists, and maps, you can effectively store and manage a variety of data in your mobile applications.


1 Comment

Leave a Reply