Thuta Learning
Dart
BasicProgrammingBeginner

What is Dart?

DartLesson 220 min

What you'll walk away with

  • Explain who develops Dart and what kinds of programs it is used for
  • Describe the three ways Dart code can run: on the VM, compiled to native code, or translated to JavaScript or WebAssembly
  • Explain what static typing and null safety catch before a program runs
  • Point out main(), a typed function, an inferred variable and a nullable variable in a small program

Explain it simply

What Dart is, simply

Dart is a general-purpose language developed by Google and released as open source. It was designed for building apps with a user interface, on phones, in browsers and on desktops, so that they are quick to write and quick to run. Today the best-known place to meet Dart is Flutter, the toolkit whose apps are written in it, but Dart also writes servers, scripts and command-line tools.

If you know Java, Kotlin, C# or TypeScript, Dart will look familiar: curly braces, classes and types. If you only know a scripting language, the new idea is that Dart wants to know the kind of every value early, so that it can warn you early.

Problem → Why → Solution

The problem: Dart refuses even your first program

Your very first Dart program is two lines long, and Dart refuses to run it. The message is hello.dart:3:23: Error: Expected ';' after this. In many scripting languages a missing line ending is forgiven, but in Dart every statement must end with a semicolon, and the error is reported at the end of the line that lacks it, not on the line that follows.

There is a larger worry behind that tiny error. A phone app is installed on thousands of devices, so a crash that a user finds is expensive, while a mistake that the compiler finds costs seconds. Dart's design answer is to catch as many mistakes as possible before the program starts: wrong syntax, values of the wrong type, and null where a real value is needed.

hello.dart
// hello.dart
void main() {
  print('Hello, Dart!')
}

Why checking early pays off

Every check that happens at compile time is a bug that can never reach a user. Dart pays for that with strictness: semicolons are required, types are known, and a variable cannot hold null unless its type says so. Getting used to that strictness on day one makes every later lesson easier.

Core concept: a checked language that can run in several ways

Dart code can run in three different ways, and the same source file can serve all of them.

ModeWhat happensTypical use
Dart VM with JITThe VM compiles just in time while the program runsDevelopment, dart run, Flutter debug builds
AOT native codeCompiled ahead of time to machine code for the target CPURelease mobile and desktop apps, command-line executables
JavaScript or WebAssemblyDart code is translated to JavaScript or WasmWeb apps that run in the browser

Whatever the target, the language rules are the same. Dart is statically typed: int, double, String and bool are types, and the compiler remembers the type of every variable and every expression. You are not forced to write types everywhere, because writing var lets Dart infer the type from the value, but once decided the type does not change. Dart's type system is sound, which means the compiler and the runtime together guarantee that a variable of type int never holds a String.

Dart 3 also has sound null safety. A type such as String can never hold null; to allow a missing value you add a question mark, as in String?. A nullable variable that has not been given a value holds null, and Dart makes you handle that case before you call methods on it. This removes a whole family of crashes that other languages only reveal at run time.

Finally, nearly everything in Dart is an object. Even the whole number 5 is an instance of int with methods such as isEven, and functions are objects that can be passed around. A program starts at the top-level function main(), statements end with a semicolon, and print() writes a value as text.

Mental model: checked first, then run anywhere
  1. Typed Dart source code
  2. Analyzer and compiler check it
  3. VM, native code or JS runs it

The language checks are the same on every target; only platform libraries differ (for example dart:io, which browsers lack).

General pattern: variables, a function and main

dart
Type name = value;            // explicit type
var name = value;             // type inferred from the value
Type? name;                   // nullable, starts as null

ReturnType name(Type param) => expression;

void main() {
  print(expression);
}

The first three lines are the three ways you will declare variables most often: with a written type, with an inferred type and with a nullable type. A function whose body is a single expression can use => instead of braces and return. Every program still needs main().

Dart in one screen

This program fits on one screen but shows four things that make Dart what it is: a typed function, an inferred variable, a nullable variable and string interpolation. Predict all four output lines, especially the last two, before you run it.

tour.dart
// A tiny program that shows what makes Dart, Dart.
int square(int n) => n * n;

void main() {
  String language = 'Dart'; // explicit type
  var chapters = 5; // type inferred: int
  int? nickname; // nullable: allowed to hold null
  print('Hello, $language!');
  print('$chapters chapters, square = ${square(chapters)}');
  print('nickname: $nickname');
  print(chapters.runtimeType);
}

Code breakdown

  1. A typed functionint square(int n) => n * n;

    => is shorthand for a body that is a single return. Both the parameter and the result are int, so square('5') would be rejected before running.

  2. An explicit typeString language = 'Dart';

    The type is written out by hand. Only a String can go into language; language = 3 would be a compile error.

  3. An inferred typevar chapters = 5;

    Dart infers int for chapters from the 5. var does not mean 'any type': chapters = 'five' later would be an error.

  4. A nullable variableint? nickname;

    The ? after int says null is allowed. No value was given, so nickname holds null. Without the ?, int nickname; would be a compile error in this program.

  5. Interpolationprint('$chapters chapters, square = ${square(chapters)}');

    $chapters inserts a variable, and ${ } inserts a whole expression such as a function call. This line prints '5 chapters, square = 25'.

  6. Types at run timeprint(chapters.runtimeType);

    runtimeType shows the real type of a value, here int. In Dart, types still exist at run time.

You should see
Hello, Dart!
5 chapters, square = 25
nickname: null
int

Dart compared with languages you may know

TopicIn Dart
TypesStatic types with inference, and unlike TypeScript the types are kept at run time
NullTypes are non-nullable by default; add ? to allow null, as in Kotlin
Division/ always returns a double, while ~/ gives an integer result
ConcurrencyOne event loop per isolate, and isolates do not share memory
SemicolonsRequired at the end of every statement

Dart 3 added records, patterns and class modifiers (sealed, base, interface, final). The later chapters teach them.

int and double: two kinds of number to remember

Dart separates whole numbers and fractional numbers into two types, int and double. The first thing to notice is that the / operator returns a double no matter what. Run the snippet below and it prints 3.5, 3, 5.0 and 5. The result of 10 / 2 is a whole value, but it is 5.0 rather than 5.

numbers.dart
void main() {
  print(7 / 2); // / always returns a double
  print(7 ~/ 2); // ~/ returns an int
  print(10 / 2); // still a double
  int whole = 10 ~/ 2;
  print(whole);
}

In real projects

Where Dart shows up in practice

In practice Dart shows up in three places. Flutter apps are the biggest: one codebase targets Android, iOS, the web and desktop, and the hot reload you use while developing comes from the VM's JIT mode. Command-line tools are the second: a Dart program can be compiled with dart compile exe into a self-contained executable that starts quickly and needs no Dart installation on the machine that runs it. The third is server and build code, where teams choose Dart so that the backend, the tooling and the app can share types and libraries.

Because the pub.dev package site and the dart command are shared by all three, what you learn in one place carries over to the others. A date-formatting package, a JSON parser or a test runner works the same whether it sits in a Flutter widget or in a command-line script.

Common mistakes

Common mistakes

1. Expecting a missing semicolon to be forgiven

The error says Expected ';' after this. and points at the end of the line that lacks the semicolon. Look at the line number in the message and add the ; at the end of that line instead of hunting on the next one.

2. Expecting JavaScript-style division

(10 + 20) / 2 prints 15.0, not 15. And int total = 10 / 2; is rejected with Error: A value of type 'double' can't be assigned to a variable of type 'int'., because / returns a double even when the result is whole. Use ~/ when you want an int.

3. Thinking Dart means Flutter

A file that imports package:flutter usually fails under dart run, because it needs libraries that only Flutter provides (such as dart:ui) and plain Dart does not include them. Keep this course's exercises in plain Dart.

Mini challenge

Mini challenge: a score report

Write two functions: average, which returns the mean of two scores as a double, and label, which accepts a null score for someone who has not been graded yet. Then call them from main().

  • average(int a, int b) must return a double (average(10, 20) prints 15.0)
  • label takes an int? score and returns 'Name: no score yet' for null, otherwise something like 'Name: 87'
  • In main(), print average(3, 4), average(10, 20), label('Aye', 87) and label('Ko', null)
  • Predict the output before running, and watch for 15.0
report.dart
// TODO: a and b are int, the return type is double
average(a, b) {
  // TODO: add the two scores and divide with /
}

// TODO: score may be missing, so its type needs a ? after int
String label(String name, score) {
  // TODO: if score is null, return '<name>: no score yet'
  // TODO: otherwise return '<name>: <score>'
}

void main() {
  // TODO: print the four results listed in the requirements
}

Expected: The program prints these four lines: 3.5 15.0 Aye: 87 Ko: no score yet

Show hint

(a + b) / 2 is a double, so give the function the return type double. In label, check if (score == null) { return ...; } first, and only then put score into the string.

Show solution
report.dart
double average(int a, int b) => (a + b) / 2;

String label(String name, int? score) {
  if (score == null) {
    return '$name: no score yet';
  }
  return '$name: $score';
}

void main() {
  print(average(3, 4));
  print(average(10, 20));
  print(label('Aye', 87));
  print(label('Ko', null));
}

Quick quiz 1 / 3

Why does Dart reject int total = 10 / 2;?

Quick quiz 2 / 3

What does the declaration String? nickname; mean?

Quick quiz 3 / 3

Which compilation mode lets Flutter apply a code change to a running app while you develop (hot reload)?

What to remember

  • Dart is a typed, null-safe, object-oriented language from Google that runs on the VM (JIT), as native code (AOT), or as JavaScript or WebAssembly
  • var infers one type and never changes it, while Type? allows null
  • / always returns a double and ~/ gives an int result
  • Every program starts at main(), and every statement ends with a semicolon

Dart 3.13 changelog — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

What is Dart? | Thuta Learning