Master Dart syntax, null safety, async/await, and core language features.
Dart Overview
Dart is a client-optimized language for fast apps on any platform. It's the language of Flutter.
Key Features
- Sound null safety - Non-nullable by default
- Ahead-of-time (AOT) compilation - Fast startup, consistent performance
- Just-in-time (JIT) compilation - Hot reload during development
- Single-threaded with async support - Event loop + isolates for concurrency
- Rich standard library - Collections, async, math, convert, etc.
Variables and Types
// Type inference (recommended)
var name = 'Dune'; // String
var year = 2021; // int
var rating = 8.5; // double
var isFavorite = true; // bool
// Explicit types when needed
String title = 'Dune';
int releaseYear = 2021;
double score = 8.5;
bool watched = true;
// Final (single assignment) - prefer over var
final immutableName = 'Dune';
// immutableName = 'Dune 2'; // Error
// Const (compile-time constant)
const pi = 3.14159;
const apiUrl = 'https://api.example.com';
// Late initialization (non-null, initialized later)
late String description;
void init() {
description = 'A sci-fi epic';
}
// Nullable types (with null safety)
String? nullableTitle; // Can be null
nullableTitle = 'Dune';
nullableTitle = null; // OK
// Non-nullable (default)
String nonNullTitle = 'Dune';
// nonNullTitle = null; // Compile errorNull Safety
// Safe navigation
String? title = 'Dune';
print(title?.length); // 4 (int?)
print(title!.length); // 4 (int, throws if null)
// Null-aware operators
String displayTitle = title ?? 'Unknown'; // Default if null
title ??= 'Default'; // Assign if null
// Conditional property access
title?.toUpperCase();
// Null check promotion
if (title != null) {
print(title.length); // title promoted to non-nullable
}
// Required keyword for mandatory parameters
class Movie {
final String title;
final int year;
// Required named parameters
Movie({required this.title, required this.year});
}Functions
// Basic function
String greet(String name) {
return 'Hello, $name!';
}
// Expression body (=>) for single expressions
String greet(String name) => 'Hello, $name!';
// Optional positional parameters
String greet(String name, [String? title]) {
return title != null ? 'Hello, $title $name!' : 'Hello, $name!';
}
// Optional named parameters
String greet({required String name, String? title, int times = 1}) {
return 'Hello, ${title ?? ''}$name! ' * times;
}
// Default parameter values
void printMovie(String title, {int year = 2024, double rating = 0.0}) {
print('$title ($year) - $rating/10');
}
// Anonymous functions (lambdas)
var movies = ['Dune', 'Blade Runner'];
movies.forEach((movie) => print(movie));
// Higher-order functions
List<String> upperMovies = movies.map((m) => m.toUpperCase()).toList();
// Function as first-class citizen
void Function(String) printer = print;
printer('Hello');
// Typedef for function types
typedef MovieFilter = bool Function(Movie movie);
List<Movie> filterMovies(List<Movie> movies, MovieFilter filter) {
return movies.where(filter).toList();
}Control Flow
// If-else
if (rating >= 9) {
print('Masterpiece');
} else if (rating >= 7) {
print('Great');
} else {
print('Watchable');
}
// Switch expression (Dart 3+)
String description = switch (rating) {
>= 9 => 'Masterpiece',
>= 7 => 'Great',
>= 5 => 'Good',
_ => 'Watchable',
};
// Switch with patterns
switch (movie) {
case Movie(title: var t, year: var y) when y > 2020:
print('Recent: $t');
case Movie(title: var t):
print('Classic: $t');
default:
print('Unknown');
}
// Loops
for (var i = 0; i < movies.length; i++) {
print(movies[i]);
}
for (final movie in movies) {
print(movie);
}
movies.forEach((movie) => print(movie));
// While / do-while
while (movies.isNotEmpty) {
print(movies.removeLast());
}Collections
Lists
// Immutable
final immutableMovies = ['Dune', 'Blade Runner', 'Arrival'];
// Mutable
var mutableMovies = <String>['Dune'];
mutableMovies.add('Interstellar');
mutableMovies.addAll(['Arrival', 'Contact']);
// Spread operator
var allMovies = [...immutableMovies, ...mutableMovies];
// Collection if/for
var sciFiMovies = [
'Dune',
if (includeBladeRunner) 'Blade Runner',
for (var movie in moreMovies) movie,
];
// Common operations
movies.map((m) => m.toUpperCase()).toList();
movies.where((m) => m.length > 5).toList();
movies.fold('', (acc, m) => '$acc$m, ');
movies.any((m) => m.startsWith('D'));
movies.every((m) => m.length > 3);Maps
// Immutable
final ratings = {'Dune': 8.5, 'Blade Runner': 8.2};
// Mutable
var mutableRatings = <String, double>{};
mutableRatings['Dune'] = 8.5;
mutableRatings['Arrival'] = 8.0;
// Access
double duneRating = ratings['Dune']!; // Non-null assertion
double? maybeRating = ratings['Unknown']; // Nullable
// Operations
ratings.forEach((title, rating) => print('$title: $rating'));
ratings.keys; // Iterable<String>
ratings.values; // Iterable<double>
ratings.entries; // Iterable<MapEntry<String, double>>Sets
// Unique values
final genres = {'Sci-Fi', 'Thriller', 'Drama'};
var mutableGenres = <String>{'Sci-Fi'};
mutableGenres.add('Action');Classes
// Basic class
class Movie {
final String id;
final String title;
final int year;
double rating;
// Constructor
Movie({
required this.id,
required this.title,
required this.year,
this.rating = 0.0,
});
// Named constructor
Movie.unknown() : id = '', title = 'Unknown', year = 0;
// Methods
bool isRecent() => year > DateTime.now().year - 5;
// Override
@override
String toString() => '$title ($year)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Movie && runtimeType == other.runtimeType && id == other.id;
@override
int get hashCode => id.hashCode;
}Data Classes (Freezed/Json_serializable)
// With freezed (recommended for immutable data)
import 'package:freezed_annotation/freezed_annotation.dart';
part 'movie.freezed.dart';
part 'movie.g.dart';
@freezed
class Movie with _$Movie {
const factory Movie({
required String id,
required String title,
required int year,
@Default(0.0) double rating,
List<String>? genres,
}) = _Movie;
factory Movie.fromJson(Map<String, dynamic> json) => _$MovieFromJson(json);
}
// Usage
var movie = Movie(id: '1', title: 'Dune', year: 2021);
var copy = movie.copyWith(rating: 9.0); // Immutable updateGenerics
// Generic class
class Result<T> {
final T? data;
final String? error;
Result.success(this.data) : error = null;
Result.error(this.error) : data = null;
bool get isSuccess => error == null;
}
// Generic function
T? firstOrNull<T>(List<T> list) {
return list.isEmpty ? null : list.first;
}
// Constraints
class Repository<T extends Entity> {
// T must extend Entity
}Async Programming
Futures
// Future represents a value that will be available later
Future<String> fetchTitle() async {
await Future.delayed(Duration(seconds: 1));
return 'Dune';
}
// Consuming futures
void main() async {
// await (sequential)
var title = await fetchTitle();
print(title);
// Parallel with Future.wait
var results = await Future.wait([
fetchTitle(),
fetchYear(),
fetchRating(),
]);
}
// Error handling
Future<String> fetchTitle() async {
try {
var response = await http.get(Uri.parse('https://api.example.com/movie'));
if (response.statusCode == 200) {
return jsonDecode(response.body)['title'];
}
throw Exception('Failed to load');
} catch (e) {
// Handle error
return 'Unknown';
}
}
// Timeout
await fetchTitle().timeout(Duration(seconds: 5), onTimeout: () => 'Timeout');Streams
// Stream represents multiple async values over time
Stream<int> countStream(int max) async* {
for (var i = 1; i <= max; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
// Consuming streams
void main() async {
await for (var value in countStream(5)) {
print(value); // Prints 1, 2, 3, 4, 5 with 1s delay
}
// Transform
var doubled = countStream(5).map((x) => x * 2);
// Listen (imperative)
var subscription = countStream(5).listen(
(value) => print(value),
onError: (e) => print('Error: $e'),
onDone: () => print('Done'),
);
// Cancel when done
subscription.cancel();
}Isolates (True Parallelism)
// Isolates run on separate threads (no shared memory)
import 'dart:isolate';
void heavyComputation(SendPort sendPort) {
// Do heavy work
var result = 0;
for (var i = 0; i < 100000000; i++) {
result += i;
}
sendPort.send(result);
}
void main() async {
var receivePort = ReceivePort();
await Isolate.spawn(heavyComputation, receivePort.sendPort);
var result = await receivePort.first;
print('Result: $result');
// For Flutter: use compute() for simple cases
import 'package:flutter/foundation.dart';
var result = await compute(heavyFunction, largeData);
}Mixins and Extensions
// Mixin - reuse code across classes
mixin Timestamped {
DateTime createdAt = DateTime.now();
DateTime? updatedAt;
void touch() => updatedAt = DateTime.now();
}
class Movie with Timestamped {
final String title;
Movie(this.title);
}
// Extension - add methods to existing types
extension MovieExtensions on Movie {
String get formattedTitle => '$title (${year})';
bool get isHighlyRated => rating >= 8.0;
}
// Usage
var movie = Movie('Dune');
print(movie.formattedTitle);
print(movie.isHighlyRated);Enums and Sealed Classes
// Enhanced enums (Dart 3+)
enum MovieStatus {
unreleased('Coming Soon'),
released('Now Playing'),
archived('Vault');
final String label;
const MovieStatus(this.label);
}
// Sealed classes for exhaustive matching
sealed class MovieResult {
const MovieResult();
}
class Success extends MovieResult {
final Movie movie;
const Success(this.movie);
}
class Error extends MovieResult {
final String message;
const Error(this.message);
}
class Loading extends MovieResult {
const Loading();
}
// Exhaustive switch
void handleResult(MovieResult result) {
switch (result) {
case Success(movie: var m):
print('Loaded: ${m.title}');
case Error(message: var msg):
print('Error: $msg');
case Loading():
print('Loading...');
}
}Try It
Run these examples in DartPad (dartpad.dev) or create a Flutter project and test in main.dart.
void main() {
// Test null safety
String? nullable = 'Hello';
print(nullable?.length);
print(nullable!.length);
// Test collections
var movies = ['Dune', 'Blade Runner', 'Arrival'];
var upper = movies.map((m) => m.toUpperCase()).toList();
print(upper);
// Test async
Future.delayed(Duration(seconds: 1), () => print('Delayed!'));
print('Immediate');
}Build a movie data model
- Create a Movie class with id, title, year, rating, genres
- Add fromJson/toJson for serialization
- Use freezed for immutable data class
- Create a MovieRepository with async methods
- Test with mock data
- Handle errors with
Result<T>pattern
Dart has sound null safety - non-nullable by default. Use final for immutable variables, const for compile-time constants. Async/await with Futures and Streams for async programming. Freezed generates boilerplate for data classes. Isolates provide true parallelism.
Resources
- Dart Language Tour: https://dart.dev/guides/language/language-tour
- Dart Null Safety: https://dart.dev/null-safety
- Effective Dart: https://dart.dev/effective-dart
- Freezed Package: https://pub.dev/packages/freezed
- JSON Serialization: https://docs.flutter.dev/data-and-backend/json