Learn Dart Β· 2/12

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.

dart
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).

dart
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.

dart
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).
dart
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 const helps 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.

  1. int: Whole numbers without decimals. (Used for loops, counts, array indexes).
  2. double: Floating-point numbers with decimals. (Used for prices, physics, opacity).
dart
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").

dart
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).

dart
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.

dart
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.
dart
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.

dart
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).
dart
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.

dart
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

  1. var: I change.
  2. final: I set once.
  3. const: I am eternal (compile-time).
  4. dynamic: I am chaos (avoid me).
  5. $: 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.

  1. Declare a final integer variable named userId and assign it the value 12345.
  2. Declare a var string variable named username and initialize it with the value " new_user " (note the spaces).
  3. Declare a const double variable named appVersion and set it to 1.0.
  4. Declare a var boolean variable named isActive and set its initial value to true.
  5. Declare a final string variable named cleanedUsername. Its value should be the username variable with all leading/trailing whitespace removed and converted to uppercase.
  6. Declare a final multi-line string variable named profileBio. Use string interpolation to embed the cleanedUsername and appVersion values. The string should be formatted exactly as follows, with the placeholders replaced:
    apache
    Profile for [CLEANED_USERNAME]
    Active on App Version: [APP_VERSION]
  7. Declare a dynamic variable named userPreferences and initialize it with null.

Expected result

Your code should correctly declare seven variables inside the main function, following all instructions.

  • userId should be final userId = 12345;. It's final because a user ID is assigned once at runtime and should not change.
  • username should be var username = " new_user ";. It's var because a username might be updated by the user later.
  • appVersion should be const appVersion = 1.0;. It's const because the app version is a fixed value known at compile-time.
  • isActive should be var isActive = true;. The user's active status can change, so var is appropriate.
  • cleanedUsername should be final cleanedUsername = username.trim().toUpperCase();. It's final as it's a derived, single-assignment value. It must use the trim() and toUpperCase() methods.
  • profileBio should be a final multi-line string using triple quotes ('''). It must use string interpolation ($cleanedUsername and $appVersion) to display the required text.
  • userPreferences should be dynamic userPreferences = null;. The dynamic keyword is required as specified to allow for type flexibility, which should be used with caution.
dart

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.