Dart Handbook
Dart is a statically typed language used by Flutter and for command-line programs. A Dart program starts at its top-level main function.
Pick Dart when
- You want to share a Flutter UI across platforms. A shared widget tree can cover most screens, while plugins connect to platform services such as the camera.
- You want to reuse application logic outside the UI. Put validation, data models, or file processing in a Dart package that you can test separately or use from a command-line tool.
Think twice before choosing Dart when
- Your app depends on a platform-specific SDK. Check early whether a Dart package supports that SDK on every target platform.
- Your team needs to extend an existing web or server application. Check whether the required libraries and deployment tools support Dart before introducing a second toolchain.
Dart vs. its closest alternatives
Choose Dart when Flutter is your UI framework. TypeScript fits teams building on JavaScript browser and server libraries. Kotlin fits projects centered on the JVM or native Android APIs.
Your First Program
Install Dart tooling using the Resources links. Save this program as hello.dart.
The entry point is main. Final prevents reassigning names, and join reads the list to build the string printed by print.
void main() {
final names = ["Ada", "Lin"];
print(names.join(" and "));
}Run these commands from the directory containing the source file. The output is Ada and Lin
dart run hello.dartResources
- Dart language documentation
- Dart SDK and command-line tools
- Dart API reference
- DartPad
- Dart and Flutter packages
- Flutter documentation
Use Dart 3 or later. Save a standalone example as main.dart and run it with the Dart SDK. The testing section gives separate instructions.
dart run main.dartTopics
Variables & Constants
Use var to infer a static type. A final collection can still be mutated, while a const collection is immutable.
The initializer fixes count as an int, so adding 2 gives 3. Labels still refers to the same list after add changes its contents. Calling add on priorities would fail because the list itself is constant.
Reassign a variable and mutate a list
void main() {
var count = 1;
count += 2;
final labels = <String>['new'];
labels.add('done');
const priorities = [1, 2, 3];
print([count, labels, priorities]); // [3, [new, done], [1, 2, 3]]
}Choose a compile-time constant
void main() {
const first = [1, 2];
const second = [1, 2];
print(identical(first, second)); // true
}The two const lists have the same canonical instance, so identical prints true.
Types & Null Safety
String? allows null. The ?. operator skips the method call when the value is null, and ?? supplies a fallback. Use final for a variable assigned once and const for a compile-time constant.
Passing null skips trim and selects Dart as the recipient. The named argument overrides the default prefix, so the program prints Welcome, Dart!
Read a nullable value
String greeting(String? name, {String prefix = 'Hello'}) {
final recipient = name?.trim() ?? 'Dart';
return '$prefix, $recipient!';
}
void main() {
const prefix = 'Welcome';
print(greeting(null, prefix: prefix));
}Narrow a nullable parameter
String label(String? name) {
if (name == null) return 'Guest';
return name.toUpperCase();
}
void main() {
print(label(null)); // Guest
print(label('Ada')); // ADA
}The early return handles null. On the remaining path Dart promotes name to String.
Strings & Interpolation
Use interpolation to build strings and a raw string for a regular expression with backslashes.
Dart strings are immutable. Trim returns the text without surrounding whitespace. The raw regex finds one or more digits, and group(0) returns the full match. The null-aware call allows for inputs without digits.
Extract and interpolate text
void main() {
final input = ' Order 42 '.trim();
final number = RegExp(r'\d+').firstMatch(input)?.group(0);
print('Order number: $number'); // Order number: 42
}Handle a missing match
void main() {
final match = RegExp(r'\d+').firstMatch('Order pending');
print(match?.group(0) ?? 'No order number');
}FirstMatch returns null for this input. The fallback supplies the displayed label.
Functions & Named Parameters
Named parameters can have defaults. A function can also accept another function as an argument.
Fold starts the running total at zero. The supplied function doubles each value before adding it, so the result is 12. When the caller omits transform, the fallback uses each original value.
Pass a callback by name
int total(List<int> values, {int Function(int)? transform}) {
return values.fold(0, (sum, value) => sum + (transform?.call(value) ?? value));
}
void main() {
print(total([1, 2, 3], transform: (value) => value * 2)); // 12
}Set a default for a named parameter
String repeat(String text, {int copies = 1}) =>
List.filled(copies, text).join(' ');
void main() {
print(repeat('tea')); // tea
print(repeat('tea', copies: 2)); // tea tea
}The first call uses one copy. The second call names copies explicitly and produces two copies.
Collections & Control Flow
Lists hold ordered values, sets hold unique values, and maps associate keys with values. Collection for and if clauses can build a list from only the entries that satisfy a condition.
Each map entry has a key and a value. The collection loop checks the price and adds only the key for entries costing at most 3, producing Tea and Water.
Filter items in a list literal
void main() {
final prices = <String, int>{'Tea': 3, 'Coffee': 5, 'Water': 2};
final affordable = [
for (final entry in prices.entries)
if (entry.value <= 3) entry.key,
];
print(affordable); // [Tea, Water]
}Spread an optional list
List<String> menu(List<String>? extras) => ['Tea', ...(extras ?? const <String>[])];
void main() {
print(menu(null)); // [Tea]
print(menu(['Coffee'])); // [Tea, Coffee]
}The fallback supplies an empty list when extras is null. Spread inserts the chosen list’s elements.
Maps & Sets
Use Map.update to count words. A set built from the same input keeps each distinct word once.
The first occurrence of tea uses ifAbsent to insert 1. Its second occurrence runs the update callback and increments the count to 2. Converting the words to a set discards the duplicate.
Count values and find unique items
void main() {
final words = 'tea coffee tea'.split(' ');
final counts = <String, int>{};
for (final word in words) {
counts.update(word, (count) => count + 1, ifAbsent: () => 1);
}
print(counts); // {tea: 2, coffee: 1}
print(words.toSet()); // {tea, coffee}
}Supply a value only when a key is absent
void main() {
final prices = {'Tea': 3};
prices.putIfAbsent('Tea', () => 9);
prices.putIfAbsent('Coffee', () => 5);
print(prices); // {Tea: 3, Coffee: 5}
}PutIfAbsent keeps Tea at 3 and inserts Coffee with value 5.
Iterable Transformations
Use where to filter values and map to transform them. The iterable is lazy, and toList materializes the result.
The filter keeps 7 and 9. Mapping doubles those two values and toList runs the pipeline, producing [14, 18]. Without toList, traversal performs the work when the iterable is read.
Filter, transform and materialize
void main() {
final prices = [4, 7, 9, 2];
final doubled = prices
.where((price) => price >= 5)
.map((price) => price * 2)
.toList();
print(doubled); // [14, 18]
}Compare a lazy view with a snapshot
void main() {
final values = [1, 2];
final doubled = values.map((value) => value * 2);
final snapshot = doubled.toList();
values.add(3);
print(doubled.toList()); // [2, 4, 6]
print(snapshot); // [2, 4]
}The lazy iterable sees the added value when traversed. The earlier list keeps its original values.
Classes & Constructors
A constructor can initialize a field directly with this.field. Named parameters make calls readable, and required marks parameters the caller must supply.
The initial task uses the default false for done. Complete creates a second task with the same title and done set to true, which is the value printed.
Construct and complete a task
class Task {
final String title;
final bool done;
const Task({required this.title, this.done = false});
Task complete() => Task(title: title, done: true);
}
void main() {
final task = const Task(title: 'Learn Dart').complete();
print(task.done); // true
}Compute a property from instance state
class Rectangle {
final int width;
final int height;
const Rectangle(this.width, this.height);
int get area => width * height;
}
void main() {
print(const Rectangle(3, 4).area); // 12
}Reading area calls the getter, which multiplies the stored dimensions.
Interfaces & Mixins
Use implements for a contract and with to reuse a mixin implementation. The on constraint gives the mixin access to the contract.
Person provides the name required by Named. Contact inherits that member and applies Described, so the mixin can read Ada when describe is called.
Implement an interface and apply a mixin
abstract interface class Named {
String get name;
}
mixin Described on Named {
String describe() => 'Name: $name';
}
class Person implements Named {
@override
final String name;
Person(this.name);
}
class Contact extends Person with Described {
Contact(super.name);
}
void main() {
print(Contact('Ada').describe()); // Name: Ada
}Swap implementations behind one interface
abstract interface class Label {
String text();
}
class Pending implements Label {
@override
String text() => 'Pending';
}
class Done implements Label {
@override
String text() => 'Done';
}
void show(Label label) => print(label.text());
void main() {
show(Pending()); // Pending
show(Done()); // Done
}The function accepts any Label implementation. The two calls use different text.
Extension Methods
An extension adds methods or getters to an existing type. Dart resolves the extension from the receiver’s static type.
Inside the getter, this is the receiver string. The regex matches each run of non-whitespace characters. Counting the matches gives 2 even with surrounding spaces.
Add a getter to strings
extension WordCount on String {
int get wordCount => RegExp(r'\S+').allMatches(this).length;
}
void main() {
print(' hello Dart '.wordCount); // 2
}Select an extension through its static type
extension TimeUnits on int {
int get secondsFromMinutes => this * 60;
}
void show(Object value) {
if (value is int) print(value.secondsFromMinutes);
}
void main() => show(2); // 120The type check promotes value to int, so the extension becomes available inside the branch.
Generics
A type parameter preserves the element type from input to output. Returning T? also accounts for an empty iterable.
MoveNext positions the iterator at the first element when one exists. The Object bound excludes nullable elements, so null unambiguously represents an empty input in this example.
Retrieve an optional generic element
T? firstOrNull<T extends Object>(Iterable<T> items) {
final iterator = items.iterator;
return iterator.moveNext() ? iterator.current : null;
}
void main() {
final int? number = firstOrNull([42, 99]);
final String? word = firstOrNull(<String>[]);
print([number, word]); // [42, null]
}Restrict a type argument by a bound
T larger<T extends num>(T a, T b) => a > b ? a : b;
void main() {
final int result = larger(3, 7);
print(result); // 7
}The num bound makes comparison available. Inference keeps the result an int for these inputs.
Enums, Records & Pattern Matching
Use an enum for a closed set of values and a record to group related values. A switch expression can match both together.
The first field selects the matching enum case. The pattern binds the second field to id, so the done record produces Completed task 7.
Match enum variants in a record
enum State { pending, done }
String describe((State, int) task) => switch (task) {
(State.done, final id) => 'Completed task $id',
(State.pending, final id) => 'Pending task $id',
};
void main() {
print(describe((State.done, 7))); // Completed task 7
}Match a list by shape
String describe(List<int> values) => switch (values) {
[] => 'Empty',
[final first, ...] => 'Starts with $first',
};
void main() {
print(describe([])); // Empty
print(describe([7, 8])); // Starts with 7
}The first arm handles the empty list. The second binds the first item and accepts any remaining elements.
Async & Error Handling
A Future represents a result or error that may arrive later. Await pauses the current async function until the future completes. Use an on clause to handle a specific exception type.
The valid input prints 3 after the delay. Change the input to oops to see how a parsing error completes the future with an error and reaches the FormatException handler at await.
Await an asynchronous result
Future<int> parseQuantity(String input) async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return int.parse(input);
}
Future<void> main() async {
try {
final quantity = await parseQuantity('3');
print(quantity);
} on FormatException {
print('Enter a whole number.');
}
}Wait for independent futures together
Future<void> main() async {
final first = Future.value('Tea');
final second = Future.value('Coffee');
print(await Future.wait([first, second])); // [Tea, Coffee]
}Both futures are created before waiting. Future.wait returns results in input order.
Streams
A stream yields zero or more values over time. An async generator produces those values and await for consumes them.
Each yield emits one value. The consumer receives 3, 2, and 1 on separate lines. When the generator exits its loop, the stream closes and the consumer finishes.
Yield and consume stream values
Stream<int> countdown(int start) async* {
for (var value = start; value > 0; value--) {
yield value;
}
}
Future<void> main() async {
await for (final value in countdown(3)) {
print(value); // 3, 2, 1 on separate lines
}
}Filter a stream before collecting it
Future<void> main() async {
final source = Stream.fromIterable([1, 2, 3, 4]);
final evens = await source.where((value) => value.isEven).toList();
print(evens); // [2, 4]
}The filter drops odd values and toList completes after the stream closes.
Isolates
On native Dart, use Isolate.run for CPU-bound work that would otherwise block the main isolate. The result comes back as a Future.
The callback computes the sum in another isolate. Await retrieves the result without making the main isolate perform the loop. The program prints 333833500.
Return a computation from an isolate
import 'dart:isolate';
int sumSquares(int limit) {
var sum = 0;
for (var n = 1; n <= limit; n++) {
sum += n * n;
}
return sum;
}
Future<void> main() async {
final result = await Isolate.run(() => sumSquares(1000));
print(result); // 333833500
}Observe that isolate state is separate
import 'dart:isolate';
int count = 1;
int increment() => ++count;
Future<void> main() async {
print(await Isolate.run(increment)); // 2
print(count); // 1
}The worker changes its own copy of count. The caller still sees 1.
Exceptions & Cleanup
Use on to catch a specific exception and finally to perform cleanup whether the operation succeeds or fails.
Parsing oops throws before the outer print receives a number. The handler prints the invalid input, then finally prints the completion message.
Catch a format error and run cleanup
void main() {
try {
print(int.parse('oops'));
} on FormatException catch (error) {
print(error.source); // oops
} finally {
print('Finished reading input.');
}
}Throw an error when an input violates a rule
int quantity(int value) {
if (value < 0) throw ArgumentError.value(value, 'value');
return value;
}
void main() {
try {
print(quantity(-1));
} on ArgumentError {
print('Invalid quantity');
}
}The guard raises ArgumentError before returning the negative input. The typed handler prints the fallback message.
JSON Encoding & Decoding
Decode JSON at the boundary and validate its shape before using fields. A map pattern can check the keys and value types together.
The pattern binds name only when it is a string and stock only when it is an integer. With stock set to 4, the encoded output has inStock set to true. A string value for stock would reach the error branch.
Decode and validate an inventory item
import 'dart:convert';
void main() {
final decoded = jsonDecode('{"name":"Tea","stock":4}');
if (decoded case {'name': String name, 'stock': int stock}) {
print(jsonEncode({'name': name, 'inStock': stock > 0}));
// {"name":"Tea","inStock":true}
} else {
throw const FormatException('Invalid inventory item');
}
}Reject a valid JSON value with the wrong shape
import 'dart:convert';
void main() {
final decoded = jsonDecode('{"stock":"4"}');
print(switch (decoded) {
{'stock': int stock} => 'Stock: $stock',
_ => 'Invalid stock',
}); // Invalid stock
}Decoding succeeds, but the pattern rejects stock because its value is a string.
File I/O
Use dart:io in native programs. Await reads and writes, and use a temporary directory to make the example safe to rerun.
Awaiting the write before the read ensures the message is available when the file is opened for reading. The finally block deletes the temporary directory even if an operation fails.
Write and read a temporary file
import 'dart:io';
Future<void> main() async {
final directory = await Directory.systemTemp.createTemp('dart-guide-');
try {
final file = File.fromUri(directory.uri.resolve('notes.txt'));
await file.writeAsString('Read the Dart handbook.');
print(await file.readAsString());
} finally {
await directory.delete(recursive: true);
}
}Append a line to a file
import 'dart:io';
Future<void> main() async {
final directory = await Directory.systemTemp.createTemp('dart-guide-');
try {
final file = File.fromUri(directory.uri.resolve('notes.txt'));
await file.writeAsString('Tea\n');
await file.writeAsString('Coffee\n', mode: FileMode.append);
print(await file.readAsLines()); // [Tea, Coffee]
} finally {
await directory.delete(recursive: true);
}
}Append mode preserves the first line. ReadAsLines returns both lines in order.
Packages & Tooling
A package declares dependencies in pubspec.yaml. Keep reusable code under lib and import it with the package name. Run these commands in a terminal to create the package used by the testing example.
Run dart pub get after changing dependency declarations so imports resolve against the packages selected for this project.
Create and check a package
dart create -t package inventory
cd inventory
dart pub add --dev test
dart format .
dart analyzeResolve dependencies and run tests
dart pub get
dart testRun these commands in the inventory package. Pub get resolves declared dependencies, and dart test runs its test suite.
Testing
Test both a list with values and an empty list. Save this file as test/total_test.dart in the package created above, then run dart test.
The populated case checks the calculation and the empty case checks the starting value. A failure identifies which input no longer meets its expected result.
Test ordinary and empty inputs
import 'package:test/test.dart';
int total(Iterable<int> values) => values.fold(0, (sum, value) => sum + value);
void main() {
test('adds the values', () {
expect(total([2, 3, 5]), 10);
});
test('returns zero for empty input', () {
expect(total([]), 0);
});
}Assert that a call throws
import 'package:test/test.dart';
void main() {
test('rejects malformed quantities', () {
expect(() => int.parse('oops'), throwsFormatException);
});
}The matcher invokes the closure and checks that parsing fails with FormatException.
Best Practices
Immutable Models
Use final fields for a stable model and create a new instance when an update is needed. Copy mutable collections at the boundary to protect the model from later changes.
List.unmodifiable snapshots the constructor input. Clearing the source therefore leaves Tea in the cart. Add returns a new cart with Coffee appended.
Copy input and return a new cart
class Cart {
final List<String> items;
Cart(Iterable<String> items) : items = List.unmodifiable(items);
Cart add(String item) => Cart([...items, item]);
}
void main() {
final source = ['Tea'];
final cart = Cart(source);
source.clear();
print(cart.items); // [Tea]
print(cart.add('Coffee').items); // [Tea, Coffee]
}Expose a read-only snapshot
void main() {
final source = ['Tea'];
final snapshot = List.unmodifiable(source);
source.add('Coffee');
print(snapshot); // [Tea]
}List.unmodifiable copies the current elements. Adding an item to source leaves the snapshot unchanged.
Choosing an Async API
Choose by the shape of the result and the kind of work. An asynchronous file read can return one future while a stream suits repeated updates. CPU-intensive computation on native Dart can use a separate isolate.
- Return a Future for a single result, such as loading one file.
- Return a Stream for a sequence, such as updates from a file watcher.
- Use an isolate for expensive native computation and await the result.
Load one result with a future
Future<String> loadLabel() async => 'Tea';
Future<void> main() async {
print(await loadLabel()); // Tea
}Await retrieves the single result when it becomes available.
Read several updates from a stream
Future<void> main() async {
final updates = Stream.fromIterable(['pending', 'ready']);
await for (final update in updates) {
print(update); // pending, then ready
}
}Await for receives each update and exits when the stream closes.