Dart Tutorial
Learn Dart step by step: 61 lessons in 11 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Dart? Find out what Dart is, who made it, where it runs (Flutter, servers, command-line tools, the web), how JIT and AOT compilation work, and how this tutorial runs its examples.
- Installing the Dart SDK and Tooling Install the Dart SDK, create a project with dart create, run it, add packages with dart pub, and use the analyzer, formatter, DartPad and VS Code.
- Your First Dart Program Write your first Dart program: the main function, print, comments, string interpolation and the basic structure every Dart file follows, with runnable stand-ins.
- Variables, var, final and const Learn how Dart stores values: type inference with var, explicit types, final versus const, compile-time constants and an introduction to late variables.
Types and Operators
- Numbers: int and double Learn Dart's number types: int and double, num, division with / and ~/, the modulo operator, parsing text, rounding, formatting and the dart:math library.
- Strings and String Interpolation Master Dart strings: single and double quotes, raw and multiline strings, interpolation, common methods, StringBuffer for building text, and how runes handle Unicode.
- Booleans and Operators Learn Dart's bool type and its operators: arithmetic, ~/ and %, comparison, logical short-circuiting, bitwise, cascade (..), and the is, is! and as operators.
- Null Safety: Nullable and Non-Nullable Types Understand sound null safety in Dart: nullable T? versus non-nullable T, the ?., ??, ??= and ! operators, null checks and how type promotion removes casts.
- late Variables and Lazy Initialization Learn the Dart late keyword: declare non-nullable variables that are assigned later, use late final and lazy initializers, and avoid LateInitializationError.
- The Type System: dynamic, Object and Type Inference Tour Dart's sound type system: Object and Object?, dynamic, void, Never, type inference rules, the is and as operators, runtimeType and how types relate.
- Records Learn Dart 3 records: positional and named fields, returning several values from a function, record types, structural equality and destructuring.
Control Flow
- if, else and Conditional Expressions Learn Dart conditionals: if and else if chains, the ternary operator, ?? for defaults, collection if and else inside list, set and map literals, and guard clauses.
- Loops: for, while and do-while Learn Dart loops: the classic for loop, for-in over collections, while and do-while, break, continue and labels, with runnable TypeScript stand-ins.
- switch Statements and Expressions Learn Dart 3 switch: statements without fall-through, switch expressions, exhaustiveness checks for enums and sealed classes, and guard clauses with when.
- Patterns and Destructuring Learn Dart 3 patterns: destructure lists, maps, records and objects, use if-case and switch, and know the main pattern types, with runnable stand-ins.
Functions
- Functions Learn how to declare and call Dart functions: return types, void, arrow syntax, nested functions, lexical scope and recursion, with runnable stand-ins.
- Positional, Named and Optional Parameters Learn Dart function parameters: required positional, optional positional in brackets, named parameters in braces, default values and the required keyword.
- First-Class Functions, Closures and Typedefs Learn how Dart treats functions as values: function types, anonymous functions, closures that capture variables, typedef aliases and tear-offs.
Collections
- Lists Learn Dart lists: growable and fixed-length lists, adding and removing items, sublists, sorting, the spread operator, collection if and collection for, with examples.
- Sets Learn Dart sets: unique elements, set literals vs maps, union, intersection and difference, how equality works, and LinkedHashSet, HashSet and SplayTreeSet.
- Maps Learn Dart maps: literals, reading and updating keys, nullable lookups, putIfAbsent and update, iterating entries, spread and collection for, and key equality rules.
- Iterables and Functional Collection Methods Learn Dart Iterable methods: map, where, fold, reduce, expand, any, every, take and skip, why they are lazy, and when to call toList to get a real collection.
- The dart:collection Library Learn the dart:collection library: Queue, ListQueue, DoubleLinkedQueue, LinkedList, HashSet, LinkedHashSet, HashMap, SplayTreeMap and unmodifiable views, and when to pick each.
- Generics Learn Dart generics: generic classes and functions, type inference, bounds with extends, covariance and its runtime checks, and why Dart generics are reified.
Classes and Object-Oriented Dart
- Classes and Objects Learn Dart classes and objects: declaring fields and methods, creating instances without new, the this keyword, toString, cascades, and library-level privacy with underscores.
- Constructors Learn every kind of Dart constructor: generative, named, initializing formals, initializer lists, redirecting, factory and const constructors, with examples.
- Getters, Setters and Properties Learn Dart getters and setters: computed properties, validation on assignment, read-only fields, and how library-level privacy replaces private keywords.
- Inheritance and Polymorphism Learn Dart inheritance and polymorphism: extends, super, @override, abstract members, calling parent constructors, covariant parameters and dynamic dispatch.
- Abstract Classes and Implicit Interfaces Understand Dart abstract classes, why every class is also an interface, how implements differs from extends, and what the Dart 3 interface class modifier adds.
- Mixins Learn how Dart mixins share behavior across unrelated classes: the mixin and with keywords, on constraints, mixin class, and the order in which mixins stack.
- Class Modifiers: sealed, final, base Learn the Dart 3 class modifiers abstract, base, final, interface and sealed, what each one forbids, and how sealed hierarchies give exhaustive switches.
- Enums and Enhanced Enums Learn Dart enums: declaring values, the values list, name and index, switch exhaustiveness and enhanced enums with fields, constructors, methods and interfaces.
- Extension Methods and Extension Types Learn how Dart extension methods add members to existing types, how to name and scope them, and how extension types wrap a value with zero runtime cost.
- Operator Overloading, ==, hashCode and toString Learn how to overload operators in Dart, follow the equality contract with == and hashCode, implement Comparable and write a useful toString for your classes.
- Static Members, Constants and Callable Classes Learn Dart static fields and methods, static constants, const constructors and canonical instances, the singleton pattern with factories, and callable classes.
Errors and Libraries
- Exceptions and Error Handling Learn Dart error handling: throw, try/catch/on/finally, Exception versus Error, rethrow, stack traces and how to design your own custom exception classes.
- Assertions and Debugging Learn how to find Dart bugs faster: assert statements and debug mode, print debugging, the debugger, DevTools, logging with levels and stack traces.
- Libraries, Imports and Packages Learn how Dart organizes code into libraries and packages: import, as, show, hide, deferred loading, export, part files, pubspec.yaml, version constraints and pub.dev.
- Core Libraries: dart:core, math, convert, collection A tour of Dart's built-in libraries: DateTime and Duration, RegExp, jsonEncode and jsonDecode, Uri, Random, dart:math and dart:collection, with runnable stand-ins.
- Files, Directories and Command-Line Programs Read and write files, list directories, take command-line arguments, read stdin, set exit codes and run other programs with Dart's dart:io library.
Asynchronous Dart
- Futures and async/await Understand Dart Futures: async and await, then and catchError, error handling, running tasks in parallel with Future.wait, timeouts and common mistakes.
- Streams Learn Dart streams: single-subscription and broadcast streams, listen and await for, StreamController, async* generators, transformations and cancelling subscriptions.
- The Event Loop, Microtasks and Zones See how Dart runs async code on one thread: the event queue, the microtask queue, the order of futures and timers, why blocking code freezes everything, and what zones do.
- Isolates and Concurrency Learn how Dart runs work in parallel with isolates: Isolate.run, ports, message passing and why nothing is shared, with runnable stand-ins.
Real-World Dart
- JSON and Serialization Turn JSON into typed Dart objects and back: jsonDecode, jsonEncode, fromJson and toJson, nested objects, lists and the json_serializable idea.
- HTTP Clients and Servers Call REST APIs with package:http, handle status codes and timeouts, and write small servers with dart:io HttpServer and shelf, with runnable stand-ins.
- Testing with package:test Write Dart tests with package:test: test, group, expect, matchers, setUp, async tests and fakes instead of mocks, with a runnable plain-assertion stand-in.
- Effective Dart: Style, Lints and Formatting Write idiomatic Dart: naming conventions, analysis_options.yaml, lint rules, dart format, dart fix and documentation comments, with runnable stand-ins.
- Performance and Memory Make Dart programs fast: JIT versus AOT, const objects, fewer allocations, lazy iterables, StringBuffer, typed data, profiling and honest benchmarks.
- From Dart to Flutter and Dart on the Server See where your Dart skills lead: Flutter widgets and hot reload, calling C with dart:ffi, talking to JavaScript with js_interop, and every compile target.
- Common Dart Mistakes and Pitfalls Avoid the Dart bugs that trip up almost everyone: overusing the ! operator, forgetting await, forEach with async, list equality, const lists and shared fills.
Projects
- Project: Todo Command-Line App Build a todo app for the terminal in Dart: an immutable model, sealed commands parsed with patterns, a pure core, JSON file storage and tests.
- Project: Bank Account Model Model a bank in Dart: a Money extension type, accounts with inheritance, sealed Result types for expected failures, exceptions for broken rules and records.
- Project: Expression Evaluator Build a calculator engine in Dart: tokenize text, parse it with recursive descent into a sealed AST, evaluate it with pattern matching and simplify it.
- Project: Async Event Pipeline Build a stream pipeline in Dart: an async* source, where and asyncMap stages, batching, back-pressure with await for, and graceful or hard cancellation.
- Project: Typed REST Client Build a typed REST client in Dart: JSON models with fromJson, sealed API errors, a retry helper with backoff and a client class, with runnable TypeScript stand-ins.
Practice and Review
- Practice: Basics and Control Flow Seven Dart exercises with solutions on variables, strings, null safety, loops, switch expressions and patterns. Try each one first, then compare with the answer.
- Practice: Classes and Collections Seven Dart exercises with solutions on classes, sealed hierarchies, generics, maps, grouping, value equality and enhanced enums, with runnable stand-ins.
- Practice: Async and Streams Seven Dart exercises with solutions on Futures, Future.wait, timeouts, async* generators, stream pipelines, broadcast controllers and event-loop ordering.
- Dart Interview Questions 30 Dart interview questions with concise answers on null safety, const vs final, mixins, class modifiers, futures, streams, the event loop, isolates and compilation.
- Dart Cheat Sheet A one-page Dart cheat sheet: variables, null safety, strings, collections, functions, classes, patterns, async, streams and everyday commands, with short examples.