Sub topic 1
Where can a Flutter app keep data?
Almost every real app needs to remember something after it closes: a theme choice, a login token, a list of notes. This chapter maps the places a Flutter app can keep data on the device, what each one costs, and how they differ. Later chapters cover each option in depth.
Prerequisites
This chapter assumes you already know:
- Basic Dart syntax, including classes and null safety.
- Asynchronous Dart:
Future,asyncandawait. - How to build a simple Flutter app with widgets and state.
- How to add a package with
flutter pub addor by editingpubspec.yaml.
You do not need any database knowledge. SQL is introduced when it is needed.
Memory is not storage
Variables, setState values and objects held by state-management libraries live in RAM. The operating system can end your app's process at any time, for example when memory is low or the user swipes it away. Everything in RAM disappears then.
Persistent storage means writing data to the device's disk so a later launch can read it back. The choice among persistence options comes down to a few questions:
- How big is the data, and how is it shaped?
- How sensitive is it?
- Do you need to search or filter it?
- Must it survive an app reinstall or move to a new phone?
The app sandbox
Both Android and iOS give each app a private area of disk, called a sandbox. Other apps cannot read it, and the OS deletes it when the user uninstalls your app. Every on-device option in this chapter lives inside that sandbox, except where a package explicitly says otherwise.
This has two consequences:
- Data in the sandbox is private to your app, but it is only as safe as the device. On a rooted or jailbroken device, or in an unencrypted backup, it can be read. That is why secrets need a separate option.
- Local data is local. It does not sync between devices and is gone if the user uninstalls. If losing it would hurt the user, you need a server or a cloud backup as well.
The main options
Flutter does not ship a storage layer. You pick a package built on a platform feature.
| Option | Typical package | Best for | Not suited for |
|---|---|---|---|
| Key-value store | `shared_preferences` | Small settings: flags, numbers, short strings | Large data, lists of records, secrets |
| Files | `path_provider` with `dart:io` | Documents, images, exported data, cached downloads | Frequent small updates, searching |
| Secure storage | `flutter_secure_storage` | Tokens, passwords, encryption keys | Bulk data |
| SQLite database | `sqflite`, or `drift` on top | Structured, related data you filter, sort and update | Tiny settings (too much ceremony) |
| Embedded NoSQL or object store | Hive, Isar, ObjectBox, sembast | Object-shaped data without SQL | Data with many relations and ad hoc queries |
Key-value storage
A key-value store maps string keys to a few primitive types: bool, int, double, String and List<String>. Under the hood shared_preferences uses SharedPreferences on Android, NSUserDefaults on iOS and localStorage in web browsers. Its API is tiny, so it is the quickest way to persist a setting.
The platform implementations are meant for small values. Treat the store as configuration, not as a place for records. The classic API also loads all values into memory when you first call getInstance(), so large content slows startup.
Files
A file is the most flexible option. You choose the format: JSON, CSV, an image, a PDF. The path_provider package tells you which directory to use, because paths differ by platform and cannot be hardcoded. Directory choice matters. Some directories are backed up and kept, while others can be cleared by the OS when space is low.
Files suit whole-document data. If you save one JSON file with all your notes, you must read and rewrite the entire file to change one note. That is fine for dozens of items and painful for tens of thousands.
Secure storage
flutter_secure_storage stores small strings using the platform's protected facilities. It uses the Keychain on iOS and Android's Keystore-backed encryption on Android. Use it for anything an attacker would value, such as authentication tokens. Reads and writes are slower than preferences, and the data model is the same simple key and string value. Do not use it as a general database.
SQLite
SQLite is a small relational database engine stored in a single file. You define tables with typed columns, then insert, query, update and delete rows with SQL. It handles large collections efficiently, supports filtering and sorting in the database rather than in Dart, and can change several rows atomically in a transaction. The sqflite package exposes it on Android and iOS. Packages such as drift add type-safe queries and generated code on top.
Embedded NoSQL
Several packages store Dart objects or JSON-like documents directly, with no SQL. They can be faster to start with and fit object-shaped data well. The trade-off is that each has its own query model, and some (Hive and Isar in particular) have had uncertain maintenance, so check a package's current status before committing to it.
A quick demonstration
The smallest useful persistence example counts how many times the app has launched. Add shared_preferences to your project, then run this as lib/main.dart:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
final launches = (prefs.getInt('launch_count') ?? 0) + 1;
await prefs.setInt('launch_count', launches);
runApp(
MaterialApp(
home: Scaffold(
body: Center(child: Text('Launch number $launches')),
),
),
);
}Stop the app completely and start it again. The number goes up each time because the value survives the process. Uninstalling resets it, since the sandbox is deleted. A hot reload does not restart main, so it will not increase the count.
Comparing the options on the questions that matter
The choice follows from four properties of your data.
- Size and shape. A handful of independent values points to key-value storage. A document or binary blob points to files. Many records of the same shape point to a database.
- Sensitivity. Anything that grants access to an account or decrypts other data belongs in secure storage, never in plain preferences or a plain file.
- Query needs. If you must ask "all notes tagged X, newest first", a database does that in one statement. With files or preferences you would load everything and filter in Dart.
- Change frequency. Frequently updated small pieces suit a database, which changes rows in place. A file must be rewritten as a whole, which risks losing data if the app is killed mid-write.
The diagram turns these questions into a rough decision path. The final chapter returns to this in detail.
Common mistakes
- Putting secrets in
shared_preferences. Preferences are plain text on disk and can appear in device backups. Tokens belong in secure storage. - Using preferences as a database. Encoding a list of records as one big JSON string inside a preference works at first. It then slows startup and cannot be queried.
- Forgetting that storage is asynchronous. Every call here returns a
Future. Reading a value withoutawaitgives you aFuture, not the value, and a write you never awaited may not have finished when you read it back. - Assuming it exists on every platform. Web, desktop and mobile differ. In browsers,
sqfliteis not supported out of the box, and preferences are stored inlocalStorage, which has a size cap of several megabytes. Check each package's supported-platform list before relying on it. - Treating local data as a backup. If the data matters beyond one install, sync it somewhere else too.
What comes next
The remaining chapters follow the dependency order of the options. They start with shared_preferences, then cover serialization, directories, files and secure storage. They go on to SQLite with sqflite, parameterized queries and schema migrations, then briefly cover drift and NoSQL options. They end with the repository pattern, testing and the final decision guide.
Exercise
You are building a notes app. It must store (a) the user's preferred font size, (b) a refresh token for the user's account, and (c) 5,000 notes that the user can search by title and sort by date. Name the storage option you would choose for each and give one reason for each choice.
Show answer
(a) sharedpreferences: it is a single small primitive setting, and the key-value API is the simplest fit. (b) fluttersecure_storage: the token grants access to the account, so it needs the Keychain or Keystore-backed protection, not plain preferences. (c) SQLite through sqflite (or drift): thousands of same-shaped records that must be filtered by title and sorted by date, which a database does with a query. Rewriting a whole file for every edit would be slow, and filtering in Dart would mean loading everything.
Exercise
A teammate saves a list of 2,000 orders as one JSON string in shared_preferences and says "it works on my phone". Describe two problems this design will cause as the app grows.
Show answer
First, the classic shared_preferences API loads all values into memory at startup, so a large string slows launch and raises memory use. Second, the value cannot be queried or updated in part: changing one order means decoding, editing and rewriting the whole string, and finding orders by a field means loading them all and filtering in Dart. A file, or better a SQLite table, would fit this data. Other acceptable answers: the platform stores may limit value sizes (for example localStorage on web), and a failed write can corrupt or lose the entire list.