Dart Cheatsheet — Concise Reference
A cheatsheet for Dart 3 syntax, type system, async and the most-used standard libraries — covering ~80% of daily work.
Dart Dart 3
Dart SDK · OO · Generic · Functional · Async-first · Static (sound null safety)
Recommended Learning Path
Start with dart create/run and the pubspec layout → grasp variables, types and control flow → dig into functions, strings and collections → understand classes, mixin and error handling → write concurrent code with isolates and async/await → then learn networking, time, processes, regex, and build & test as needed. The FAQ chapter is your go-to for avoiding pitfalls later.
1.Hello World & Runtime
Minimal program, dart create/run, and project structure.
Minimal program
Every Dart program starts from a void main() entry function. dart run executes it, and print outputs to stdout.
Create & run
dart create scaffolds a standard project; dart run executes the entry file directly. Use JIT for fast iteration during development and AOT for efficient release builds.
Project structure
pubspec.yaml declares the package name, dependencies and SDK constraint. Code lives in lib/ and bin/, tests in test/.
Print output
print writes to stdout and appends a newline. Use $ to interpolate a variable, ${expr} for expressions.
Command-line arguments
main can accept a List<String> args parameter. args[0] is the first positional argument; the program name is not included.
Async main function
main may return Future<void>; the program waits for all awaits to finish before exiting — useful for time-consuming work.
Comments
Use // for single-line, /// for documentation (used by dart doc), and /* */ for block comments. Comments don't affect execution.
Top-level members
Dart allows top-level functions and variables (outside any class). import libraries to use their public API; top-level variables are visible across the file.
2.Variables & Constants
Variable declarations, final/const, null safety, and destructuring.
var and final
var declares a variable that can be reassigned but its inferred type is fixed. final declares a variable that can only be assigned once.
const constants
const is a compile-time constant; the value must be known at compile time. const values are canonicalized — identical literals share one instance.
Explicit types
You can annotate variables with explicit types. Static types help the compiler — annotate public APIs explicitly.
Nullable variables
Under sound null safety, types are non-nullable by default. Append ? to allow null; null-check or use ?? for a default value.
late lazy initialization
late defers initialization until first access. late final allows only one assignment — perfect for fields that depend on runtime values.
Destructuring assignment
Dart 3 supports records and pattern destructuring — bind multiple values at once. The pattern must match the shape.
Scope & shadowing
A variable is visible within its block; inner scopes may shadow outer ones. Top-level variables are visible across the library.
dynamic and Object
dynamic bypasses static checks; the type is resolved at runtime. Object is the root of the type hierarchy and requires explicit casts.
3.Data Types
Built-in types, collection types, records, and enums.
Numeric types
int is an integer; double is a double-precision float; num is their supertype. An int literal is assignable to double.
String type
String is an immutable sequence of UTF-16 code units. Single and double quotes are equivalent; interpolation and multiline literals are supported.
Boolean type
bool has only true and false. Conditional expressions must return bool — there is no implicit numeric conversion.
List type
List is an ordered, growable collection supporting generics. Literal [a, b] creates a list, growable by default.
Set and Map
Set is an unordered, unique-element collection; Map is a key-value collection. Both are generic and have literal syntax.
Record type
Dart 3 Records are unnamed, lightweight aggregates. They can have named fields and work with pattern destructuring.
Enums
enum defines a fixed set of named constants. Enhanced enums (Dart 2.17+) can carry fields and methods.
Type conversion
int.parse / double.parse convert a string to a number, toString converts back, and as performs a runtime cast.
4.References & Null Safety
Object references, null safety, deep copies, and native memory.
Object references
Dart has no raw pointers — variables hold references to objects. Assignment copies the reference; multiple variables can point to the same object.
Null safety
Sound null safety restricts null to nullable types like String?. The compiler enforces non-null at compile time.
Null-assertion !
Appending ! asserts that a nullable expression is non-null; it throws a null check error if violated. Use it only when you're sure.
Null-coalescing
?? yields the right-hand side when the left is null. ??= assigns only if the variable is currently null.
late and const
final assigns once at runtime; const is a compile-time constant. late defers initialization — useful for expensive objects and circular dependencies.
References and equality
== defaults to reference comparison; identical() checks for the same instance. Use a helper for structural equality.
Deep vs shallow copy
A shallow copy duplicates only the top level — nested objects are still shared. Deep copy repeats per layer; immutable collections are safe to share.
Native memory
dart:ffi exposes Pointer and calloc for native memory access — used for C interop. Pointer lifetimes are the developer's responsibility.
5.Control Flow
if, loops, switch, and pattern matching.
if / else
if/else if/else branches on a condition, which must be bool. Null-checks trigger type promotion.
Ternary expression
cond ? then : else is a single-expression branch. Combine with ?? for null defaults.
for loop
Classic three-part for; for-in iterates an Iterable. Dart 3 supports pattern destructuring in the loop variable.
while loop
while checks then runs; do-while runs once then checks. Use them for loops of unknown iteration count.
switch expression
Dart 3 switch expression returns a value. Each case has a pattern; use => to produce the result — no break needed.
switch statement
switch statements branch on cases — empty cases fall through, guards and patterns are supported. Each non-empty case must break.
Pattern matching
if-case and switch perform structural matching. Combine object patterns, record patterns and guards.
break and continue
break exits the loop; continue skips to the next iteration. Labels control jumps in nested loops.
6.Functions & Lambdas
Function definitions, optional parameters, closures, and async functions.
Function definition
A function has a return type, name, parameters and body. Use void when there is no return value.
Arrow function
Single-expression bodies use => — the expression's value is returned. Great for pure functions and callbacks.
Optional positional parameters
Square brackets [] mark optional positional parameters. Defaults (or null) are used when omitted — defaults must be compile-time constants.
Named parameters
Curly braces {} mark named parameters; pass them by name. Mark with required to force the caller to provide them.
Higher-order functions
Functions are first-class — pass them as arguments or return them. map / where / fold are the standard collection higher-order helpers.
Closures
A closure captures the variables of its defining scope and can read and mutate them even after the outer function returns.
Async functions
An async function returns a Future; inside, await pauses until the result is ready. await only works inside async functions.
Generators
sync* yields a lazy Iterable; async* yields a Stream. yield emits one value; yield* delegates to another generator.
7.Strings
Literals, interpolation, substrings, encoding, and formatting.
String literals
Single and double quotes both delimit strings. Escape with backslashes, or use a raw string with the r prefix.
String interpolation
Use $var (or ${expr}) to embed a value in a string. Any object's toString is called automatically.
Multiline strings
Triple single quotes ''' start a multiline string — newlines and indentation are preserved.
Common methods
contains / startsWith test for substrings; replaceAll swaps text; toUpperCase / toLowerCase change case.
Substrings & search
substring extracts a slice; indexOf locates a substring; split breaks on a delimiter into a list.
Characters & encoding
Dart strings are UTF-16. codeUnits gives code units; runes gives code points — use runes to handle emojis.
Efficient concatenation
Repeated + concatenation allocates many temporaries. StringBuffer accumulates and produces the string in one go.
Formatting & parsing
toStringAsFixed sets decimal places; padLeft / padRight pad to a width; int.parse / double.parse parse numeric strings.
8.Collections
Lists, maps, set operations, and sorting.
List operations
add appends, insert places at index, remove deletes by value, sort orders ascending. Default List is growable and mutable.
List higher-order
map transforms, where filters, reduce / fold aggregate, expand flattens. Most return a lazy Iterable.
Spread operator
... spreads a collection's elements into a literal. ...? safely skips a null source.
Collection if/for
Use if inside collection literals to include elements conditionally, for to generate many. Dart 3 also supports pattern destructuring here.
Map operations
Iterate Map keys / values / entries. putIfAbsent fills lazily, update mutates, remove deletes.
Set operations
Set enforces uniqueness. union / intersection / difference are set operations; toSet deduplicates a list.
Sort & search
sort defaults to ascending; pass a comparator for custom order. indexOf does a linear search; contains checks membership.
Read-only collections
List.unmodifiable creates a read-only view — mutating throws UnsupportedError. List.of copies into a mutable list.
9.Memory & Performance
Garbage collection, const canonicalization, and buffer reuse.
Garbage collection
The Dart VM garbage-collects automatically — no manual free. Objects with no references become eligible for collection.
const canonicalization
const values are canonicalized — identical literals share one instance. Prefer const on hot paths.
Lazy initialization
Top-level and static variables are lazily initialized on first access. late offers the same deferred semantics.
List capacity
Growable lists resize as needed — repeated add reallocates. Pre-size when the count is known.
Buffer reuse
Uint8List and other typed-data buffers suit binary work. Reuse buffers and use StringBuffer to avoid repeated allocation.
Weak references
Expando attaches data to an object without modifying it, using a weak key. WeakReference lets the object be collected.
Object lifecycle
Objects live in their isolate's heap. Isolates don't share mutable state — only copies or messages.
Native memory
Use dart:ffi for native memory during C interop. You must manually free — otherwise you leak.
10.Object-Oriented
Classes, inheritance, mixins, and interfaces.
Classes & constructors
class declares an object blueprint. Constructors share the class name; this. params assign directly to fields.
Inheritance
extends inherits from a superclass; @override marks overrides; super calls parent members. Dart is single-inheritance.
mixin
A mixin is a reusable behavior fragment; use with to apply it. More flexible than inheritance and avoids the single-parent limit.
Abstract class
An abstract class can't be instantiated — it defines a contract that subclasses must fulfill.
Interfaces
Every class implicitly defines an interface — use implements to fulfill it. All members must be reimplemented.
Accessors
get defines a read-only accessor; set defines a writable one. Accessors read and write like fields without parentheses.
Static members
static members belong to the class, not an instance. static methods can't access instance members.
sealed class
sealed classes restrict subclasses to the same library, so exhaustive switches need no default. A Dart 3 feature.
11.Error Handling
try/catch, custom exceptions, and async errors.
try / catch
try wraps code that may throw; catch handles exceptions. catch (e) gets the exception object.
on clause
on filters the caught exception type — pair with catch to read it. Stack handlers from top to bottom.
finally and rethrow
finally always runs, for cleanup. rethrow propagates the original error, preserving its stack.
Throw exceptions
throw raises an exception object. Anything can be thrown, but idiomatic code throws an Exception or Error subclass.
Custom exceptions
Implement Exception for business errors. Override toString for friendly messages and carry structured fields.
Async errors
Exceptions thrown after await are catchable with try/catch. Unawaited Future errors are silently lost.
Stream errors
Pass an onError callback when listening to a Stream. StreamController.addError injects an error into the stream.
Assertions
assert checks a condition in development; it throws AssertionError on failure. Stripped from release builds.
12.Files & I/O
File I/O, JSON, and standard input and output.
Read files
The File class from dart:io reads/writes files. readAsString loads an entire text file — import 'dart:io'.
Write files
writeAsString writes text; writeAsBytes writes binary. Pass mode: FileMode.append to append.
Read line by line
readAsLines splits a file into a list of lines. For large files, use openRead with LineSplitter to stream.
JSON processing
dart:convert provides jsonEncode / jsonDecode for serialization. JSON numbers become int or double.
Standard input/output
stdin.readLineSync reads a line synchronously; stdout.writeln writes a line. Ideal for CLI programs.
Directory operations
Directory.list enumerates entries; create makes a directory; delete removes one. Returned entities are FileSystemEntity.
Binary bytes
readAsBytes reads binary; Uint8List models bytes; writeAsBytes writes them. Suitable for images, audio, etc.
Path operations
File / Directory expose the full .path. .absolute resolves the absolute path; .uri gives a file:// URI.
13.Common Pitfalls
The pitfalls you are most likely to hit in everyday Dart development, and how to write it correctly.
Misusing null-assertion
Bypassing null checks with ! often crashes at runtime. Prefer null-checks, ??, and type promotion.
Collection == comparison
List / Map == compares by reference, not contents. Use a helper for structural equality.
const vs final
const requires a compile-time value; final accepts a runtime value. Writing const for runtime data fails compilation.
Lazy Iterable
map / where return lazy Iterables that recompute on iteration. Snapshot with toList when needed.
Forgetting await
Calling an async function without await gives you a Future, not its result. Use Future.wait for parallelism.
Cascade returns receiver
The cascade .. returns the receiver, not the last expression's value. Don't cascade when you need the result.
Modifying during iteration
Adding or removing during iteration throws ConcurrentModificationError. Use removeWhere or collect first.
Strings by code units
length counts UTF-16 code units — Chinese and emoji take more than one. Iterate runes for real characters.
14.Concurrency & Async
Isolates, Future, Stream, and the event loop.
Isolate concurrency
An isolate is Dart's concurrency unit — its own memory and event loop. Start with Isolate.run or Isolate.spawn.
spawn & ports
Isolate.spawn starts an isolate with an entry function. SendPort sends, ReceivePort receives.
Future basics
Future represents a result that's available later. Future.value resolves immediately; await waits.
async / await
async marks an async function; await pauses for the Future. await is only valid inside async.
Stream
A Stream is a sequence of async events. Use listen to subscribe, await for to iterate. Different from Future's single value.
StreamController
StreamController drives a stream manually — add pushes data, addError pushes errors, close ends it. broadcast enables multi-listeners.
Waiting for multiple Futures
Future.wait waits for all to complete; Future.any resolves with the first to finish.
Completer
Completer gives you manual control over a Future's completion — handy for wrapping callback APIs in async/await.
15.Networking
HTTP requests, WebSocket, and TCP sockets.
HTTP client
Use dart:io's HttpClient for HTTP. getUrl returns a request; close it and read the body.
package:http
package:http wraps common requests. http.get / http.post return a Response whose body is a string.
URI parsing
Uri.parse parses a URL; queryParameters reads the query string; Uri.http builds a request URL.
JSON API
Call a JSON API and parse the response with jsonDecode. Combine package:http with Future.
WebSocket
WebSocket is full-duplex. WebSocket.connect establishes the link; add sends; iterate to receive.
TCP socket
Socket.connect establishes a TCP connection. Write the request, stream the response. Good for low-level protocols.
HTTP server
HttpServer.bind starts a local server, then await for iterates over requests. Great for dev tools.
Timeouts & errors
Network calls may time out or fail. Use .timeout and catch each error type explicitly.
16.Time & Date
DateTime, Duration, formatting, and timestamps.
Current time
DateTime.now() returns the current local time. All fields are accessible, including milliseconds.
Constructing time
DateTime(year, month, day, ...) constructs a time; DateTime.utc constructs UTC time.
Duration
Duration represents a span of time — hours, minutes, seconds, microseconds. Supports arithmetic, comparison, and unit conversion.
Formatting output
Dart has no built-in strftime — use padLeft to zero-pad, or the intl package's DateFormat.
Parsing time
DateTime.parse reads an ISO-8601 string; toIso8601String produces one. Both ease data exchange.
Time arithmetic
add / subtract shift time by a Duration; difference returns the Duration between two times.
Timestamps
Millisecond/microsecond timestamps store and order easily. fromMillisecondsSinceEpoch rebuilds a DateTime.
Timezone
DateTime defaults to local time. Use isUtc to test; toUtc / toLocal to convert. Persist in UTC.
Stopwatch
Stopwatch measures elapsed time. start / stop / reset control it; elapsed returns a Duration.
17.Processes & Environment
Child processes, environment variables, standard streams, and signals.
Run child process
Process.run executes a command and waits. result.stdout / stderr capture the output.
Streaming process
Process.start returns immediately — stream stdout and write stdin interactively. For long-running tasks.
Environment variables
Platform.environment is a read-only Map of env vars. Missing keys return null.
Exit code
Set the process exit code via exitCode. 0 means success; non-zero signals failure categories to shells.
Args & script
args is the command-line argument list; Platform.script is the entry path; Directory.current is the cwd.
Standard streams
stdout / stderr for output, stdin for input. flush forces a buffer write; stderr skips piped output.
Filesystem
File / Directory cover the filesystem — create, delete, rename, exists.
Signal handling
ProcessSignal responds to system signals (SIGINT / SIGTERM) — for graceful shutdown and cleanup.
18.Regular Expressions
Matching, replacing, splitting, and grouping with RegExp.
Create & match
RegExp models a regular expression. hasMatch tests existence. The r prefix keeps the string raw.
First match
firstMatch returns the first match. group extracts a capture; start / end give positions. null when there's no match.
All matches
allMatches returns an iterable of matches. Combine with patterns to extract all hits.
Replacement
replaceAll swaps every match; replaceFirst swaps just the first. Pass a callback for dynamic replacements.
Split
String.split accepts a RegExp — split on a pattern. The separator itself is dropped.
Capture groups
Parentheses define capture groups. group(n) gets the nth; (?<name>...) names one for namedGroup.
Flags
Pass flags to the RegExp constructor — caseSensitive, multiLine, dotAll, unicode.
Common patterns
Store common validators — email, phone, URL, IP — as reusable constants.
19.Build & Debug
pub, static analysis, formatting, and testing.
pubspec configuration
pubspec.yaml is the package manifest — name, version, SDK constraint, dependencies. Run dart pub get to resolve.
pub commands
Manage dependencies with pub: get, upgrade, outdated, add, remove.
Static analysis
dart analyze does static analysis — run in CI to enforce quality.
Formatting
dart format enforces a consistent style — indentation, quotes, line breaks. Use in team workflows.
Unit tests
package:test provides test() and expect. Run with dart test. Place tests in test/.
Compile & deploy
dart compile produces executables: exe (native), js (web), aot-snapshot, kernel.
lint rules
Configure lints in analysis_options.yaml. The lints package ships a recommended set.
Debugging
print is the simplest debugger. assert checks invariants; IDE breakpoints step through code.
About this Cheatsheet
This is a self-contained cheatsheet for Dart 3, covering the language core and the most-used standard libraries for ~80% of real-world code. It leans toward modern idioms — sound null safety, records and patterns, switch expressions, sealed class, cascade operator, and isolate-based concurrency. Dart is designed by Google and powers Flutter; it ships with both JIT (fast iteration) and AOT (efficient release) execution. For the authoritative reference, see the official Dart language tour and Effective Dart. The 19 chapters each focus on one topic — from your first program through isolates, common pitfalls, build & test. Every chapter is split into 8 short, runnable examples (5–15 lines each), totalling about 152 topics. Snippets are intentionally short and self-explanatory; comments are kept in Chinese to support language learners. All processing happens in your browser — nothing is uploaded or tracked. This page is part of GuruToolkit's free developer toolkit; snippets are free to use with no warranty.
Version 2.1.0