Dart Language Essentials
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Dart is the language Flutter apps are written in. It is a statically typed, garbage-collected, object-oriented language
with sound null safety, a modern pattern-matching feature set, and first-class asynchronous programming. The examples on
this page target Dart 3.13.7, the version bundled with Flutter 3.47.9 (see
Getting Started with Flutter), and use the running Trailhead hiking-journal
app from the rest of this section: a list of trails served by https://api.example.com/v1, favourites, and hike logging.
Variables, Types and Sound Null Safety
Dart infers types with var and final, and declares compile-time constants with const. Every type is non-nullable by
default; a trailing ? makes it nullable, and the compiler proves that a non-nullable value can never be null (this is
what "sound" means, and the compiler uses it to generate faster code).
final name = 'Camino de Santiago'; // inferred String, assigned once
var lengthKm = 12.5; // inferred double, reassignable
const maxResults = 50; // compile-time constant
late final String token; // assigned later, exactly once
int count = 0; // never null
void main() {
String? nickname; // may be null; a local, so it can be promoted
print(nickname?.toUpperCase()); // null-aware call: null when nickname is null
print(nickname ?? 'unnamed'); // default value
nickname ??= 'Trail Runner'; // assign only when null
if (nickname != null) {
print(nickname.length); // promoted to String inside the branch
}
}
Type promotion works for local variables and private final fields (Dart 3.2+); top-level variables, public fields and mutable fields are not promoted, so copy them to a local first.
The built-in types you meet most often are int, double, num, bool, String, List, Set, Map, Object,
Object?, dynamic (opts out of static checking, avoid) and Never. Strings support interpolation with $name and
${expr}.
Functions, Parameters and Classes
Dart has positional, optional positional and named parameters. Named parameters are central to Flutter widget constructors:
required makes a named parameter mandatory, and this.field initializes a field directly.
class Trail {
const Trail({
required this.id,
required this.name,
required this.lengthKm,
required this.difficulty,
});
factory Trail.fromJson(Map<String, dynamic> json) => Trail(
id: json['id'] as String,
name: json['name'] as String,
lengthKm: (json['lengthKm'] as num).toDouble(),
difficulty: Difficulty.values.byName(json['difficulty'] as String),
);
final String id;
final String name;
final double lengthKm;
final Difficulty difficulty;
}
enum Difficulty {
easy('Easy'),
moderate('Moderate'),
hard('Hard');
const Difficulty(this.label);
final String label;
}
Notable class features: const constructors let Flutter skip rebuilding unchanged widgets; factory constructors are the
idiomatic home for fromJson; a name that starts with an underscore is private to its library (normally the file), not
to the class; and class modifiers (abstract, base, final, interface, sealed, mixin) control how a class may be
extended outside its library.
Records
A record is an anonymous, immutable, fixed-size aggregate with structural equality. Records let a function return several values without declaring a class.
(double lat, double lon) currentPosition() => (41.3874, 2.1686);
void main() {
final (lat, lon) = currentPosition(); // destructuring
print(currentPosition() == (41.3874, 2.1686)); // true: structural equality
}
Patterns and Switch Expressions
Patterns match the shape of a value and bind variables in one step. They appear in switch, if-case, variable
declarations and for loops. Dart 3 switch has no fall-through and can be used as an expression.
String badge(Difficulty d) => switch (d) {
Difficulty.easy => 'green',
Difficulty.moderate => 'amber',
Difficulty.hard => 'red',
};
void handle(Object? json) {
if (json case {'id': String id, 'name': String name}) {
print('Trail $id is $name'); // map pattern with type tests
}
if (json case [var first, ...var rest] when rest.isNotEmpty) {
print('first=$first'); // list pattern with guard
}
}
The compiler checks switches over enums and sealed types for exhaustiveness: forgetting a case is a compile error rather than a runtime surprise.
Sealed Classes and Exhaustive Switch
A sealed class can only be extended inside its own library, so the compiler knows every direct subtype. It is the natural
way to model a result or UI state, and Trailhead uses it to represent the loading state of the trail list.
sealed class TrailsState {
const TrailsState();
}
class TrailsLoading extends TrailsState {
const TrailsLoading();
}
class TrailsLoaded extends TrailsState {
const TrailsLoaded(this.trails);
final List<Trail> trails;
}
class TrailsFailed extends TrailsState {
const TrailsFailed(this.message);
final String message;
}
String title(TrailsState state) => switch (state) {
TrailsLoading() => 'Loading',
TrailsLoaded(:final trails) => '${trails.length} trails', // object pattern
TrailsFailed(:final message) => 'Error: $message',
};
Adding a fourth subtype makes every non-exhaustive switch over TrailsState fail to compile, which is exactly the
refactoring safety net that Kotlin sealed interfaces and TypeScript discriminated unions provide.
Extension Types, Mixins and Extension Methods
An extension type is a zero-cost wrapper around an existing type: it gives a different static interface with no runtime object allocation. It is useful for type-safe identifiers.
extension type TrailId(String value) {
bool get isValid => value.isNotEmpty;
}
Mixins reuse behaviour across class hierarchies, and extension methods add members to types you do not own:
mixin Loggable {
void log(String message) => print('[$runtimeType] $message');
}
extension TrailListX on List<Trail> {
List<Trail> search(String q) => where((t) => t.name.contains(q)).toList();
}
Collections, Spread and Collection-if/for
List, Set and Map have literal syntax, and the literals support spread (..., ...?), if and for inside the
literal. Flutter code uses this constantly to build children lists conditionally.
final favourites = <String>{'t1', 't7'};
final tags = ['hike', if (favourites.isNotEmpty) 'starred', for (var i = 1; i <= 3; i++) 'day$i'];
final byId = {for (final t in trails) t.id: t}; // map comprehension
final totalKm = trails.fold<double>(0, (sum, t) => sum + t.lengthKm);
Prefer the iterable methods (where, map, fold, any, every) over index loops; they are lazy until toList().
Dot Shorthands and Null-aware Elements
Two newer conveniences are part of the Dart 3.13 baseline. Dot shorthands omit the type name when the context type is
known (Difficulty level = .moderate;), and null-aware elements add an item to a collection literal only when it is
non-null (['Trailhead', ?subtitle]). Both are optional sugar; the other pages of this section write the fully
qualified form so that code reads the same on older SDKs.
Asynchronous Programming
Dart is single-threaded per isolate, with an event loop. Long waits (network, disk) do not block the thread because they
return a Future, a value that will be available later. async and await let you write the code sequentially.
Future<List<Trail>> fetchTrails() async {
final response = await http.get(Uri.parse('https://api.example.com/v1/trails'));
if (response.statusCode != 200) {
throw HttpException('Unexpected status ${response.statusCode}');
}
final list = jsonDecode(response.body) as List<dynamic>;
return [for (final item in list) Trail.fromJson(item as Map<String, dynamic>)];
}
A Stream is a sequence of asynchronous events. async* functions produce streams with yield, and await for consumes
them:
Stream<int> countdown(int from) async* {
for (var i = from; i >= 0; i--) {
await Future<void>.delayed(const Duration(seconds: 1));
yield i;
}
}
Future<void> run() async {
await for (final n in countdown(3)) {
print(n);
}
}
The http, dio, geolocator and camera packages all expose Future and Stream APIs, and Flutter widgets such as
FutureBuilder and StreamBuilder rebuild when they complete (see State
Management).
Isolates
An isolate is an independent worker with its own memory heap and event loop; isolates share nothing and communicate by
passing messages. Heavy CPU work (parsing a very large JSON document, image processing) on the main isolate drops frames
because it blocks the UI thread. Isolate.run is the one-call way to offload a computation:
import 'dart:isolate';
Future<List<Trail>> parseTrails(String body) => Isolate.run(() {
final list = jsonDecode(body) as List<dynamic>;
return [for (final item in list) Trail.fromJson(item as Map<String, dynamic>)];
});
The closure runs on a short-lived isolate, and its return value is sent back to the caller. Flutter also exposes compute,
a thin wrapper that predates Isolate.run. For long-lived workers use Isolate.spawn with ReceivePort and SendPort.
Isolates are not available on the web target, where the code runs on the main thread.
Tooling: pub, analysis_options and the dart Command
Dependencies are declared in pubspec.yaml and resolved by pub from https://pub.dev. The Flutter equivalents of the
commands below are flutter pub add, flutter pub get, flutter analyze and flutter test.
name: trailhead
environment:
sdk: ^3.13.0
dependencies:
flutter:
sdk: flutter
flutter_riverpod: ^3.5.0
The ^3.13.0 caret syntax means "compatible with 3.13.0 up to, but excluding, 4.0.0". Lint rules are configured in
analysis_options.yaml.
A typical file includes package:flutter_lints/flutter.yaml and enables stricter analyzer options such as strict-casts,
strict-inference and strict-raw-types.
| Command | Purpose |
|---|---|
|
Reformat all code with the canonical Dart style. |
|
Run the analyzer and lints ( |
|
Apply automated fixes for lints and deprecations. |
|
Run tests of a pure Dart package ( |
For Java, Kotlin and TypeScript Developers
| Concept | Java | Kotlin | Dart |
|---|---|---|---|
Null safety |
|
|
|
Immutable local |
|
|
|
Compile-time constant |
|
|
|
Data class |
|
|
class with |
Sealed hierarchy |
|
|
|
Pattern matching |
|
|
|
Async |
|
|
|
Reactive streams |
Flow, Reactor |
|
|
Concurrency |
threads |
dispatchers |
isolates, no shared memory |
Extension functions |
no |
|
|
Package manager |
Maven, Gradle |
Gradle |
pub ( |
Visibility |
|
|
leading underscore, library-private |
Compared with TypeScript, Dart has a real runtime type system (a List<int> is never a List<String> at run time),
no structural typing for classes, no undefined, and a sound null-safety guarantee that TypeScript only approximates.
Next Steps
Continue with Getting Started with Flutter and Widgets and Layout. Related reading: React Native, Kotlin Multiplatform and Hybrid Apps.