Learn Dart Β· 1/12

Introduction to Dart & Environment Setup

6 min read

Introduction to Dart & Environment Setup

Welcome to the Dart side! 🎯 If you are here, you likely want to build beautiful mobile apps with Flutter or fast server-side applications. But before we paint the Mona Lisa, we need to buy the canvas and learn how to hold the brush.

This guide covers the Dart programming languageβ€”the engine under the hood of Flutter.


1. The 'Why' Before the 'How': Why Dart?

The Problem

In the early 2010s, developers faced a dilemma.

  • JavaScript was ubiquitous but lacked type safety (making large apps messy).
  • Java was type-safe but verbose and slow to iterate (compile... wait... run).
  • Native compilation was fast for users but slow for developers.
  • Interpreted languages were fast for developers but slow for users.

You usually had to pick: Development Speed or Execution Speed.

The Solution: Dart

Google introduced Dart to bridge this gap. It is a client-optimized language for fast apps on any platform.

Key Concepts that Solve the Problem:

  1. Dual Compilation Model (The Superpower) πŸ¦Έβ€β™‚οΈ
    • JIT (Just-In-Time): Used during development. It compiles code as it runs. This enables Hot Reload (sub-second updates).
    • AOT (Ahead-Of-Time): Used for release. It compiles code into native machine code (ARM/x86) before the app runs. This makes the final app startup instant and animations smooth.
  2. Sound Null Safety:
    • Dart creates a "No Fly Zone" for null errors. If a variable can be empty, you must declare it explicitly. This prevents the "Billion Dollar Mistake" (Null Pointer Exceptions) from crashing your production app.
  3. Concurrency without Locks:
    • Dart uses Isolates (explained in section 4) instead of shared-memory threads, making it much harder to accidentally freeze your UI.

Fun Fact: Dart was originally unveiled in 2011 as a potential replacement for JavaScript in the Chrome browser. It didn't win that battle, but it found a much bigger kingdom in 2017 with the release of Flutter. 🏰


2. Setting up the Dart SDK and your IDE

We will install the Dart SDK (Software Development Kit). Even if you plan to use Flutter later, knowing how to run pure Dart code is a massive industry advantage for backend logic and scripting.

πŸ› οΈ Step 1: Install the Dart SDK

Select your operating system below. We will use the official package managers (industry standard).

πŸͺŸ Windows

We recommend using Chocolatey. Open your Command Prompt or PowerShell as Administrator:

powershell
choco install dart-sdk

Alternatively, you can download the installation wizard from the Dart website.

🍎 macOS

We use Homebrew. Open your Terminal:

bash
brew tap dart-lang/dart
brew install dart

🐧 Linux (Debian/Ubuntu)

Use apt-get with Google's official GPG key:

bash
sudo apt-get update
sudo apt-get install dart

πŸ” Step 2: Verify Installation

Close your terminal and open a new one (to refresh your PATH). Type:

bash
dart --version

If you see something like Dart SDK version: 3.x.x, you are golden! ✨

πŸ’» Step 3: IDE Setup (VS Code)

While you can use Android Studio, Visual Studio Code is the industry standard for Dart due to its speed.

  1. Download and install VS Code.
  2. Open VS Code, go to the Extensions tab (Box icon on the left).
  3. Search for Dart (published by Dart Code).
  4. Click Install.

3. Your First Dart Program: 'Hello World'

Let's write your first script.

The Code

Create a file named hello.dart. Paste the following:

dart
void main() {
  print('Hello, FreeCodeCamp!');
}

To run it, open your terminal in that folder and type:

bash
dart run hello.dart

The Breakdown (Alphabets before Words)

  1. void: This is a return type. It means "this function does its job and returns nothing."
  2. main(): This is the Entry Point. Every Dart program must have a function named main. When you run the app, Dart looks for this specific name to start executing.
  3. { ... }: These curly braces define the Scope. Everything inside is part of the main function.
  4. print(...): A built-in function that outputs text to the console.
  5. ; (Semicolon): Crucial! Dart is a C-style language. Semicolons are not optional (unlike JavaScript or Python). They tell the compiler "This instruction is finished."

Common Pitfall: If you forget the ;, the compiler will yell at you. Treat the semicolon like a period at the end of a sentence.


4. Understanding the Dart Execution Model

This is where beginners often get confused. How does Dart handle multiple tasks (like fetching data) without freezing the screen?

The Definition

Dart is Single-Threaded.
This means Dart executes one instruction at a time, sequentially.

The Concept: The Event Loop 🎑

If Dart does one thing at a time, how does it wait for a 3-second database download without stopping the whole app?

It uses an Event Loop.

Imagine a Fast Food Counter:

  1. The Worker (Main Thread): There is only one employee.
  2. The Line (Event Queue): Customers (Events) line up. These events are things like "User Tapped Button", "Timer Finished", or "Data Arrived".
  3. The Process:
    • The worker takes the first order.
    • If it's quick (math, logic), they do it immediately.
    • If it takes time (cooking/downloading), they pass a ticket to the kitchen (System/OS) and immediately take the next customer's order.
    • When the kitchen is done, the food (Data) joins the back of the line.

Visualizing the Queue

Dart actually has two lines (Queues):

  1. Microtask Queue (VIP Line): Used for internal high-priority work. The worker checks this line first. It must be empty before looking at the other line.
  2. Event Queue (Regular Line): External events like I/O, timers, gestures, drawing.

Execution Order:
Synchronous Code ➑️ Microtasks ➑️ Event Queue

πŸ—οΈ Advanced Concept: Isolates

What if you have a task so heavy (like processing a 4GB video) that it blocks the single worker for 10 seconds? The app will freeze (Anarchy!).

Solution: Spawning an Isolate.
An Isolate is like opening a second franchise location next door.

  • It has its own memory (Heap).
  • It has its own Event Loop.
  • It cannot touch the variables of the first Isolate (Memory Isolation).
  • They communicate by passing messages (like passing notes between branches).

Industry Note: You generally use the standard Event Loop (async/await) for 95% of tasks (API calls, DB reads). You only use Isolates for heavy computation (image processing, heavy JSON parsing) to keep the UI smooth.


πŸ“š References & Extra Reading

Next Up: We will dive into Variables and Data Types! Happy Coding! πŸš€

Challenge

Your task is to write a complete Dart program that demonstrates your understanding of its basic structure and core concepts.

  1. Create a multi-line comment at the top of the file explaining the primary advantage of JIT (Just-In-Time) compilation for a developer.
  2. Define the main entry point of the program using the main() function.
  3. Inside the main function, add a single-line comment that describes the purpose of an Isolate in Dart.
  4. Following the comment, use the print() function to output the exact string: "Dart's execution model is single-threaded but non-blocking."
  5. Ensure all statements are correctly terminated.

Expected result

The final code should be a syntactically correct Dart program. It must include:

  • A multi-line comment (/* ... */) at the beginning that correctly explains that JIT compilation enables features like fast development cycles and Hot Reload.
  • A void main() { ... } function block.
  • Inside the main function, a single-line comment (// ...) that correctly explains that Isolates are used for running computationally intensive tasks in the background to prevent the UI from freezing.
  • The statement print("Dart's execution model is single-threaded but non-blocking."); inside the main function, after the single-line comment.
dart

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.