Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 73 ยท Networking and data

Local Storage: SharedPreferences, SQLite and Hive

Choose the right way to save data on a Flutter device: SharedPreferences for settings, SQLite with drift or sqflite, Hive and Isar, migrations and secure storage.

Apps are closed, killed by the system and rebooted. Anything the user expects to still be there tomorrow, such as a theme choice, a login token, a draft or a shopping list, must be written to the device's storage. Flutter has no single built-in database; you choose a package that fits the size and shape of your data.

This lesson sorts the options (key-value, SQL, object stores, secure storage), shows the real API of each, explains migrations, and gives you a simple rule for picking. It builds on Futures, async/await and Streams and HTTP Requests and JSON.

Real vs stand-in. All Dart, YAML and SQL here is real and read-only: the lessons cannot read a phone's disk. The live examples are JavaScript stand-ins: an in-memory key-value store with async methods like SharedPreferences, and a tiny migration runner.

Four kinds of storage

Key-value Settings and flags.
SQL Related, queryable tables.
Object store Save Dart objects directly.
Secure storage Tokens and secrets.
1 / 2

SharedPreferences: small settings

shared_preferences stores a few simple values (bool, int, double, String, List<String>) as key-value pairs, backed by NSUserDefaults on iOS and an XML/DataStore file on Android. It is the right home for user settings and tiny flags.

DART
import 'package:shared_preferences/shared_preferences.dart';

final prefs = await SharedPreferences.getInstance();

await prefs.setBool('darkMode', true);
await prefs.setString('lastTab', 'orders');

final dark = prefs.getBool('darkMode') ?? false;     // null if missing
final tab = prefs.getString('lastTab') ?? 'home';

await prefs.remove('lastTab');

Reads are synchronous once you have the instance, writes return a Future. Always provide a default with ?? because a first launch has no keys. Newer versions also offer SharedPreferencesAsync and SharedPreferencesWithCache for apps that need consistency across isolates. Do not use it for lists of records, large JSON blobs or anything you need to query: it loads everything into memory and has no indexes.

JS A key-value store with defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

SQLite: structured data

When data has relationships and you need to filter, sort and join (orders with items, notes with tags), use SQLite. It is a real SQL database in a single file, and it ships with both mobile systems. Two common ways to use it:

  • sqflite: a thin wrapper where you write SQL strings and get maps back.
  • drift: a type-safe layer that generates Dart code from table definitions, supports streams of query results and handles migrations.

With sqflite:

DART
final db = await openDatabase(
  join(await getDatabasesPath(), 'notes.db'),
  version: 1,
  onCreate: (db, version) => db.execute('''
    CREATE TABLE notes (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title TEXT NOT NULL,
      body TEXT NOT NULL DEFAULT '',
      created_at INTEGER NOT NULL
    )
  '''),
);

final id = await db.insert('notes', {
  'title': 'Shopping',
  'created_at': DateTime.now().millisecondsSinceEpoch,
});

final rows = await db.query('notes', orderBy: 'created_at DESC', limit: 20);
await db.update('notes', {'title': 'Groceries'}, where: 'id = ?', whereArgs: [id]);

Always pass user input as whereArgs, never glue it into the SQL string, to avoid injection. SQL itself is taught in the SQL tutorial if you need a refresher.

With drift you describe tables in Dart and the generator writes the rest:

DART
class Notes extends Table {
  IntColumn get id => integer().autoIncrement()();
  TextColumn get title => text().withLength(min: 1, max: 100)();
  TextColumn get body => text().withDefault(const Constant(''))();
  DateTimeColumn get createdAt => dateTime()();
}

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

  @override
  int get schemaVersion => 1;

  Stream<List<Note>> watchNotes() =>
      (select(notes)..orderBy([(t) => OrderingTerm.desc(t.createdAt)])).watch();
}

watchNotes() returns a Stream that emits again whenever the table changes, so a StreamBuilder (FutureBuilder, StreamBuilder and Async UI) keeps the list current with no manual refresh. Run dart run build_runner build after editing the tables.

Hive and Isar: object stores

If your data is a pile of objects rather than relational tables, an object store can be simpler. Hive is a fast key-value box written in Dart; you can store maps, lists and registered adapters for your own classes. Isar is a database for Dart objects with indexes and queries. Both avoid SQL:

DART
await Hive.initFlutter();
final box = await Hive.openBox<Map>('todos');

await box.put('t1', {'title': 'Buy milk', 'done': false});
final todo = box.get('t1');                         // sync read from memory
final all = box.values.toList();

Check each package's maintenance status before you commit: Hive and Isar had long quiet periods and community forks (such as hive_ce and isar_community) appeared. A widely used database is easier to maintain for years, so for important, long-lived data, drift/SQLite is the conservative choice. Whichever you choose, wrap it behind your own repository class so the rest of the app does not depend on it.

Migrations

Your app will ship version 2 with a new column while users still hold version 1 files. A migration upgrades an existing database step by step, using a version number stored in the file.

DART
openDatabase(
  path,
  version: 3,
  onCreate: _createLatestSchema,
  onUpgrade: (db, oldVersion, newVersion) async {
    if (oldVersion < 2) {
      await db.execute('ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0');
    }
    if (oldVersion < 3) {
      await db.execute('CREATE INDEX idx_notes_created ON notes(created_at)');
    }
  },
);

Each if runs only for databases that are older than that step, so a user jumping from 1 to 3 gets both. Never edit an old step after release; add a new one. Test upgrades from every old version, because a bad migration deletes or locks out user data and you cannot fix it remotely.

JS A migration runner that upgrades step by step

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The old phone runs both steps, the newer one only the last, and a third call does nothing. That idempotent, version-gated behavior is what makes updates safe.

Secure storage for secrets

SharedPreferences and databases are stored as ordinary files. On a rooted or backed-up device they can be read. Secrets such as refresh tokens and API session keys belong in the platform's protected store: the Keychain on iOS and the Keystore (via encrypted preferences) on Android. The flutter_secure_storage package wraps both:

DART
const storage = FlutterSecureStorage();

await storage.write(key: 'refreshToken', value: token);
final saved = await storage.read(key: 'refreshToken');   // null if absent
await storage.delete(key: 'refreshToken');                // on logout

Store only small secrets there (it is slow for bulk data), delete them on logout, and remember that a key bundled in your app cannot be hidden by any storage: see Security in Flutter Apps. On iOS, Keychain items can survive an app reinstall, so decide what a fresh install should do.

Choosing quickly

Need Pick
A few settings or flags shared_preferences
Tokens, passwords flutter_secure_storage
Relational data, search, reactive lists drift (or sqflite)
Simple object boxes, offline cache Hive or Isar (check maintenance)
Files such as images and downloads path_provider plus dart:io
Data that must follow the user across devices A server or Firebase (Firebase: Auth, Firestore and Cloud Messaging)

Local storage is also a cache: show saved data first, refresh from the network, then update the UI. Many good offline apps work exactly this way.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which storage fits a dark-mode flag best?

    A single boolean setting is exactly what key-value storage is for.
  2. 2. Why pass user input through whereArgs instead of building the SQL string?

    Parameters are sent separately from the SQL text, so user input is never executed as SQL.
  3. 3. What does a database migration do?

    Migrations apply the changes between the stored version and the new version, preserving user data.
  4. 4. Where should a refresh token be stored?

    Secure storage uses the Keychain or Keystore. Plain files and constants can be read from the device or the binary.
  5. 5. What is the benefit of drift's watch() queries?

    A stream of results keeps a StreamBuilder list in sync with the database automatically.

Summary

  • Match the tool to the data: preferences for settings, SQL for related data, object stores for simple boxes, secure storage for secrets.
  • SharedPreferences reads can be null on first launch, so always use a default.
  • Use drift or sqflite for SQLite; pass inputs as parameters and keep storage behind a repository.
  • Version your schema and write step-by-step migrations that you test from every old version.
  • Local data is also a cache: show it first, then refresh from the network.

Next: Implicit Animations