Data, Storage and Networking

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Trailhead is useful on a trail with no signal, so its data layer has two jobs: talk to the REST API at https://api.example.com/v1 and keep a local copy of the trails so the list still works offline. This page builds that layer from the bottom up and hands a clean repository to the Riverpod providers from State Management. Pure Dart language features used here (sealed classes, records, pattern matching) are covered in Dart Language Essentials. The same offline problem on React Native is described in the React Native section, and the cross-platform overview is in Hybrid Apps.

Choosing a Package

Need http 1.6.0 dio 5.11.1

Simple GET and POST

Small and enough: http.get(Uri) and http.post(Uri).

Works equally well, with more setup.

Interceptors, auth refresh, retries

Wrap the client yourself with a BaseClient subclass.

Built in through Interceptor.

Upload progress, cancellation, form data

Manual.

Built in (FormData, CancelToken, progress callbacks).

Timeouts and base URL

Per-call timeouts; build URLs yourself.

Configured once through BaseOptions.

Trailhead uses dio because it needs a token refresh interceptor and a multipart photo upload. For a read-only app the http package is a fine, smaller choice.

flutter pub add dio shared_preferences path_provider drift sqlite3_flutter_libs path
flutter pub add dev:json_serializable dev:build_runner dev:drift_dev
flutter pub add json_annotation

Modelling JSON

Flutter has no runtime reflection, so JSON mapping is either hand-written or generated. For a tiny model, a manual factory constructor is clear and has no tooling cost:

class Trail {
  const Trail({
    required this.id,
    required this.name,
    required this.lengthKm,
    required this.difficulty,
  });

  final String id;
  final String name;
  final double lengthKm;
  final String difficulty; // "easy" | "moderate" | "hard"

  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: json['difficulty'] as String,
      );
}

For many models, json_serializable 6.15.2 generates the same code from annotations:

import 'package:json_annotation/json_annotation.dart';

part 'trail.g.dart';

@JsonSerializable()
class Trail {
  const Trail({
    required this.id,
    required this.name,
    required this.lengthKm,
    required this.difficulty,
  });

  final String id;
  final String name;
  final double lengthKm;
  final String difficulty;

  factory Trail.fromJson(Map<String, dynamic> json) => _$TrailFromJson(json);
  Map<String, dynamic> toJson() => _$TrailToJson(this);
}
dart run build_runner build --delete-conflicting-outputs

Note the (json['lengthKm'] as num).toDouble() idiom in the manual version: a JSON 3 decodes as an int, and casting it straight to double would throw.

Errors as Values with a Sealed Result

Network code fails in predictable ways: no connection, a timeout, an HTTP error, malformed data. A sealed class makes those outcomes part of the return type, and the compiler forces callers to handle every case:

sealed class Result<T> {
  const Result();
}

final class Success<T> extends Result<T> {
  const Success(this.value);
  final T value;
}

final class Failure<T> extends Result<T> {
  const Failure(this.error);
  final AppError error;
}

sealed class AppError {
  const AppError(this.message);
  final String message;
}

final class OfflineError extends AppError {
  const OfflineError() : super('No connection');
}

final class ServerError extends AppError {
  const ServerError(this.statusCode) : super('Server error');
  final int statusCode;
}

final class UnexpectedError extends AppError {
  const UnexpectedError(super.message);
}

Callers use an exhaustive switch:

final message = switch (result) {
  Success(:final value) => 'Loaded ${value.length} trails',
  Failure(error: OfflineError()) => 'Showing saved trails',
  Failure(:final error) => error.message,
};

Configuring dio

Dio buildDio(TokenStore tokens) {
  final dio = Dio(
    BaseOptions(
      baseUrl: 'https://api.example.com/v1',
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 20),
      headers: {'Accept': 'application/json'},
    ),
  );
  dio.interceptors.add(AuthInterceptor(dio, tokens));
  return dio;
}

Interceptor with token refresh

An interceptor can attach the access token to each request and, on a 401, refresh the token once and replay the failed request:

class AuthInterceptor extends Interceptor {
  AuthInterceptor(this._dio, this._tokens);

  final Dio _dio;
  final TokenStore _tokens;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    final token = _tokens.accessToken;
    if (token != null) options.headers['Authorization'] = 'Bearer $token';
    handler.next(options);
  }

  @override
  Future<void> onError(
    DioException err,
    ErrorInterceptorHandler handler,
  ) async {
    final alreadyRetried = err.requestOptions.extra['retried'] == true;
    if (err.response?.statusCode != 401 || alreadyRetried) {
      return handler.next(err);
    }
    try {
      await _tokens.refresh(); // uses a separate Dio instance internally
      final options = err.requestOptions..extra['retried'] = true;
      options.headers['Authorization'] = 'Bearer ${_tokens.accessToken}';
      handler.resolve(await _dio.fetch<dynamic>(options));
    } on DioException catch (e) {
      handler.next(e);
    }
  }
}

The refresh call must use a client without this interceptor, or a failing refresh would recurse. When several requests fail at once, serialise the refresh behind a single Future so that only one refresh request is sent.

The Repository Pattern

A repository hides where data comes from. The UI asks for trails; the repository decides between the network and the database.

abstract interface class TrailRepository {
  Stream<Result<List<Trail>>> watchTrails();
  Future<Result<Trail>> getTrail(String id);
  Future<Result<void>> logHike(String trailId, HikeDraft hike);
}

class ApiTrailSource {
  ApiTrailSource(this._dio);
  final Dio _dio;

  Future<List<Trail>> fetchTrails() async {
    final response = await _dio.get<List<dynamic>>('/trails');
    return (response.data ?? [])
        .cast<Map<String, dynamic>>()
        .map(Trail.fromJson)
        .toList();
  }
}

Posting a hike with its photo uses FormData and MultipartFile.fromFile against POST /trails/id/hikes.

Key-Value Storage

shared_preferences 2.5.6 stores small values (flags, the last search text, a theme choice). It is not a database and not secure storage.

final prefs = await SharedPreferences.getInstance();
await prefs.setString('lastQuery', 'ridge');
final last = prefs.getString('lastQuery') ?? '';

// Newer async API, recommended for new code.
final asyncPrefs = SharedPreferencesAsync();
await asyncPrefs.setBool('onlyFavourites', true);
final only = await asyncPrefs.getBool('onlyFavourites') ?? false;

Tokens and other secrets belong in platform secure storage. The community package flutter_secure_storage wraps the iOS Keychain and Android Keystore-backed encrypted storage; check its current version on pub.dev before depending on it. path_provider 2.1.6 gives the directories for files:

final docs = await getApplicationDocumentsDirectory(); // user data, backed up
final cache = await getApplicationCacheDirectory();    // can be cleared by the OS
final dbFile = File(p.join(docs.path, 'trailhead.sqlite'));

Offline Cache with drift

drift 2.35.4 is a type-safe reactive layer over SQLite. Tables are declared in Dart and queries return Stream values that re-emit when data changes, which suits a list screen. (The lower-level sqflite 2.4.6 is an alternative when raw SQL is enough.)

import 'package:drift/drift.dart';
import 'package:drift/native.dart';

part 'database.g.dart';

class TrailRows extends Table {
  TextColumn get id => text()();
  TextColumn get name => text()();
  RealColumn get lengthKm => real()();
  TextColumn get difficulty => text()();
  BoolColumn get favourite => boolean().withDefault(const Constant(false))();
  DateTimeColumn get cachedAt => dateTime()();

  @override
  Set<Column> get primaryKey => {id};
}

@DriftDatabase(tables: [TrailRows])
class AppDatabase extends _$AppDatabase {
  AppDatabase(super.executor);

  @override
  int get schemaVersion => 1;

  Stream<List<TrailRow>> watchAll() => select(trailRows).watch();

  Future<void> replaceAll(List<TrailRowsCompanion> rows) async {
    await transaction(() async {
      await batch((b) => b.insertAllOnConflictUpdate(trailRows, rows));
    });
  }
}

After editing the table, run dart run build_runner build to regenerate database.g.dart. Increase schemaVersion and add a MigrationStrategy when the schema changes.

Cache-then-Network

The strategy for the trail list: show whatever is stored immediately, refresh from the network, write the result back, and let the database stream update the UI.

sequenceDiagram participant UI as TrailListScreen participant Repo as TrailRepository participant DB as drift database participant API as REST API UI->>Repo: watchTrails() Repo->>DB: watchAll() DB-->>UI: Cached trails (may be empty) Repo->>API: GET /trails alt Online API-->>Repo: 200 with trail list Repo->>DB: replaceAll(trails) DB-->>UI: Fresh trails (stream re-emits) else Offline or error API-->>Repo: Failure Repo-->>UI: Keep cached data and show a banner end
class CachedTrailRepository {
  CachedTrailRepository(this._api, this._db);
  final ApiTrailSource _api;
  final AppDatabase _db;

  Stream<List<Trail>> watchTrails() => _db.watchAll().map(
        (rows) => [
          for (final r in rows)
            Trail(id: r.id, name: r.name, lengthKm: r.lengthKm, difficulty: r.difficulty),
        ],
      );

  Future<Result<void>> refresh() async {
    try {
      final trails = await _api.fetchTrails();
      await _db.replaceAll([
        for (final t in trails)
          TrailRowsCompanion.insert(
            id: t.id,
            name: t.name,
            lengthKm: t.lengthKm,
            difficulty: t.difficulty,
            cachedAt: DateTime.now(),
          ),
      ]);
      return const Success(null);
    } on DioException catch (e) {
      return Failure(switch (e.type) {
        DioExceptionType.connectionError ||
        DioExceptionType.connectionTimeout => const OfflineError(),
        _ => ServerError(e.response?.statusCode ?? 0),
      });
    }
  }
}

A real implementation preserves the favourite flag across refreshes by upserting only the API columns. Staleness is a policy decision: compare cachedAt with a time-to-live and skip the network when the data is fresh.

Connectivity

The connectivity_plus plugin reports whether a network interface is available, but "connected" does not mean "the server is reachable". Treat it as a hint to trigger a refresh, and rely on the request’s own failure for the truth. A user-facing "offline" banner should therefore appear after a failed request, not only when the radio is off.

Photos taken for a hike are covered in Platform Integration; compression and format choices are in Kotlin Multiplatform and Flutter. To test this layer with fakes, continue with Testing, and see the Flutter Cheat Sheet for a summary.