Dart Fundamentals: Variables and Data Types
7 min read
π Welcome Back, Future Dart Expert!
In the previous module, we successfully ran our first "Hello, World!" program. You stared into the console, and the console stared back. Now, it's time to actually make the computer remember things.
Imagine trying to write a novel, but every time you wanted to write the protagonist's name, you had to decide it all over again. If you decided to change the name from "Dave" to "Darth Vader" halfway through, you'd have to rewrite every single page.
This is where Variables and Data Types come in. They are the atoms and molecules of your code. Let's break them down.
1. Variables: var, final, and const
The Definition
A variable is a named location in memory used to store a value. It allows you to refer to data by a descriptive name rather than the data itself.
The Problem
Without variables, you have to hardcode values.
print(25); // What is 25? Age? Temperature? The number of bugs in my code?
print(25 + 5);If that 25 changes to 26, you have to hunt it down everywhere.
The Solution
We store the value 25 in a container named age.
Declaring Variables
Dart gives us three primary ways to declare variables depending on how "changeable" (mutable) they are.
A. var (The Standard Container)
Use var when the value might change later. Dart automatically figures out the type based on the initial value (we'll cover this magic later).
void main() {
var username = "CoderOne";
print(username);
// Later in the app, the user updates their profile
username = "CoderTwo"; // Allowed!
print(username);
}B. final (The "One-Time" Deal)
Use final when a variable will be set once and never changed again. This is heavily used in industry, especially in Flutter widgets, because immutable data makes apps faster and less bug-prone.
Standard Practice: If you don't intend to change a variable, always make it final.
void main() {
final serverUrl = "https://api.freecodecamp.org";
// serverUrl = "https://google.com"; // β Error: The final variable 'serverUrl' can only be set once.
}C. const (The Hardcoded Reality)
const is similar to final, but much stricter. A const variable must be known at compile-time. This means the computer must know the value before the program even runs.
final: "I will calculate this when the app runs, but then I'll lock it." (e.g., The exact time the user logged in).const: "I know this right now while writing the code." (e.g., The value of Pi, or the color red).
void main() {
const pi = 3.14159;
// final currentTime = DateTime.now(); // β
Allowed (Runtime value)
// const wrongTime = DateTime.now(); // β Error: DateTime.now() isn't known at compile time.
}π‘ Fun Fact: Using
consthelps Dart optimize your app's memory usage because it creates the object only once and reuses it everywhere. It's like buying one pizza and magically feeding everyone with it.
2. Built-in Types: Numbers, Strings, and Booleans
Computers are incredibly literal. They need to know if "10" is a number you can do math with, or just text that looks like a number. Dart solves this with Data Types.
A. Numbers (int and double)
Dart simplifies numbers into two specific types, both children of the parent type num.
int: Whole numbers without decimals. (Used for loops, counts, array indexes).double: Floating-point numbers with decimals. (Used for prices, physics, opacity).
void main() {
int subscribers = 1000;
double viewCount = 10.5; // Maybe you watched half a video?
// Industry Standard:
// If doing math with money, be careful with doubles due to floating-point precision errors.
// But for general use, double is your friend.
}B. Strings (String)
A sequence of characters. In Dart, you can use single quotes ' or double quotes ".
Industry Standard: The official Dart style guide prefers single quotes 'Hello' unless your string contains a single quote inside it (like "It's").
void main() {
String greeting = 'Hello freeCodeCamp';
String quote = "It's a great day to code"; // Double quotes handle the apostrophe cleanly
}C. Booleans (bool)
The simplest type. It can only be true or false. This is the brain of your logic (if this, then that).
void main() {
bool isDartCool = true;
bool isBugFixed = false;
if (isDartCool) {
print('Obviously.');
}
}3. String Interpolation and Manipulation
The Problem
In older languages, joining strings and variables was a nightmare of plus signs and closing quotes.
Old way: 'Hello user ' + username + ', you have ' + score.toString() + ' points.'
(Ugh. My eyes hurt just looking at that).
The Solution: Interpolation
Dart allows you to inject variables directly into strings using the $ symbol.
void main() {
String name = 'Quincy';
int score = 100;
// Simple variable injection
print('Player $name has entered the game.');
// Expression injection (requires curly braces)
print('Next level requires ${score + 50} points.');
}String Manipulation
Strings in Dart are immutable (you can't change them, you create new ones), but they come with powerful tools.
- Multi-line Strings: Use triple quotes (
'''or""") for long blocks of text. - Properties: Access data about the string.
void main() {
String message = ' Flutter is Awesome ';
print(message.length); // Count characters
print(message.trim()); // Removes leading/trailing whitespace (Super common in form validation!)
print(message.toUpperCase()); // SCREAMING CASE
print(message.contains('Aw')); // true
}4. Type Inference and Dynamic Types
Type Inference
Dart is smart. Extremely smart. You rarely need to explicitly type out String name = '...'. If you initialize a variable, Dart infers the type.
void main() {
// Dart sees the quotes and knows this is a String.
var city = 'Kathmandu';
// Dart sees the number and knows this is an int.
var elevation = 1400;
// elevation = 'High'; // β Error: A value of type 'String' can't be assigned to a variable of type 'int'.
}Industry Practice: Use var or final for local variables inside functions. Use explicit types (String, int) for class fields or API interfaces where clarity is crucial.
The "Danger Zone": dynamic
There is a special type called dynamic.
- Definition: A type that tells the compiler, "Trust me, I know what I'm doing. Let this variable be anything."
- Problem: It turns off the safety checks. If you try to call a method that doesn't exist on the variable, the app will crash while the user is using it (Runtime Error), not while you are coding it (Compile-time Error).
void main() {
dynamic mysteryBox = 'I am a string';
print(mysteryBox.length); // Works
mysteryBox = 99; // Totally fine, type changes to int
// mysteryBox.substring(0,1); // β CRASH! Integers don't have 'substring'.
}When to use it?
Rarely. Mostly when dealing with JSON data from an API where the structure isn't guaranteed, or when interacting with old JavaScript libraries. Avoid dynamic whenever possible. It defeats the purpose of using a type-safe language.
π§ͺ Hands-On Simulation
Let's imagine we are building a simple "User Profile" system for a game.
void main() {
// 1. CONST: The max level never changes for anyone.
const int maxLevel = 100;
// 2. FINAL: The User ID is generated once at login and shouldn't change.
final int userId = 4021;
// 3. VAR: The username might be updated by the player later.
var username = 'FastRacer';
// 4. TYPES: Stats
double winRate = 45.5;
bool isPremiumMember = false;
// 5. INTERPOLATION: Display the profile
print('''
--- PROFILE ---
ID: $userId
Player: $username
Status: ${isPremiumMember ? 'VIP' : 'Free'}
Win Rate: $winRate%
Max Level Possible: $maxLevel
''');
// Note: inside ${...} we used a "ternary operator" (isPremium ? True : False).
// We'll learn that soon, but see how clean the injection is?
}π Resources & Further Reading
π§ Quick Review
var: I change.final: I set once.const: I am eternal (compile-time).dynamic: I am chaos (avoid me).$: The magic wand for strings.
Go forth and declare variables responsibly! π
Challenge
You are tasked with setting up the initial variables for a user profile in a new Dart application. Follow the requirements below precisely.
- Declare a
finalinteger variable nameduserIdand assign it the value12345. - Declare a
varstring variable namedusernameand initialize it with the value" new_user "(note the spaces). - Declare a
constdouble variable namedappVersionand set it to1.0. - Declare a
varboolean variable namedisActiveand set its initial value totrue. - Declare a
finalstring variable namedcleanedUsername. Its value should be theusernamevariable with all leading/trailing whitespace removed and converted to uppercase. - Declare a
finalmulti-line string variable namedprofileBio. Use string interpolation to embed thecleanedUsernameandappVersionvalues. The string should be formatted exactly as follows, with the placeholders replaced:apacheProfile for [CLEANED_USERNAME] Active on App Version: [APP_VERSION] - Declare a
dynamicvariable nameduserPreferencesand initialize it withnull.
Expected result
Your code should correctly declare seven variables inside the main function, following all instructions.
userIdshould befinal userId = 12345;. It'sfinalbecause a user ID is assigned once at runtime and should not change.usernameshould bevar username = " new_user ";. It'svarbecause a username might be updated by the user later.appVersionshould beconst appVersion = 1.0;. It'sconstbecause the app version is a fixed value known at compile-time.isActiveshould bevar isActive = true;. The user's active status can change, sovaris appropriate.cleanedUsernameshould befinal cleanedUsername = username.trim().toUpperCase();. It'sfinalas it's a derived, single-assignment value. It must use thetrim()andtoUpperCase()methods.profileBioshould be afinalmulti-line string using triple quotes ('''). It must use string interpolation ($cleanedUsernameand$appVersion) to display the required text.userPreferencesshould bedynamic userPreferences = null;. Thedynamickeyword is required as specified to allow for type flexibility, which should be used with caution.