Sub topic 14
Choosing the right option
By now you have seen the main ways a Flutter app can keep data on the device: shared_preferences, plain files, flutter_secure_storage and SQLite through sqflite. This chapter turns those tools into a decision. It assumes you can write async Dart, you have added packages through pubspec.yaml, and you have read the earlier chapters on each storage option.
The goal is not to find the best option. Each option fits a different kind of data. Most real apps use two or three of them side by side.
The four questions
Ask these questions about each piece of data, in this order.
- Is it secret? Tokens, passwords and API keys belong in secure storage. This question comes first because a "yes" overrides the others.
- How big is it? A few values are small. A photo, a download or a large export is big.
- What shape does it have? A single value, a document, or many related records.
- How will you read it? Do you load everything at once, or search, filter, sort and update single items?
Work through the questions for each kind of data separately. A settings screen, an auth token and a list of 50,000 notes need different answers.
Comparing the options
| Option | Best for | Size | Querying | Protected at rest |
|---|---|---|---|---|
| `shared_preferences` | Settings, flags, last-used values | Small (a few KB total) | Read by key only | No |
| Files (`path_provider`) | Documents, exports, cached downloads, images | Small to very large | None built in | No, unless you encrypt |
| `flutter_secure_storage` | Tokens, keys, credentials | Very small values | Read by key only | Yes, via platform keystore |
| SQLite (`sqflite`) | Many records that you filter, sort and update | Thousands to millions of rows | Full SQL | No, unless you use an encrypted build |
The last column deserves attention. Only secure storage uses the platform keystore (Keychain on iOS, Keystore-backed encryption on Android). Preferences, files and a default SQLite database are readable by anyone who can access the app's data, for example on a rooted device or from an unencrypted backup.
A decision flow
The diagram below follows the four questions as a path. Start at the top and stop at the first box that matches.
Worked scenarios
A settings screen
A dark mode switch, a language code and the last selected tab are small, independent values. You read them at startup and write them when the user changes them. Use shared_preferences.
import 'package:shared_preferences/shared_preferences.dart';
Future<void> saveDarkMode(bool value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('dark_mode', value);
}
Future<bool> loadDarkMode() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool('dark_mode') ?? false;
}Do not store a growing list in preferences. Preferences are loaded into memory as a whole, so a large value slows startup for every read.
A login session
An authentication token is a credential. Putting it in preferences would leave it readable in plain text. Use secure storage.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const _storage = FlutterSecureStorage();
Future<void> saveToken(String token) =>
_storage.write(key: 'auth_token', value: token);
Future<String?> readToken() => _storage.read(key: 'auth_token');
Future<void> clearToken() => _storage.delete(key: 'auth_token');Keep only the secret there. If you also want to remember the user's display name, that can go in preferences.
A small list that is always loaded whole
Suppose you keep a few dozen bookmarks, and the app always shows all of them. A JSON file is enough. You read the file, decode it into a list, and write the whole list back after a change. This is simple and needs no schema.
The cost grows with the list. Every change rewrites the entire file, and two writes that overlap can overwrite each other. If the list grows past a few hundred items, or you need to search it, move to SQLite.
A notes app
Notes are many records of the same shape. Users search them by title, edit one at a time and delete single items. These are database operations. Use SQLite.
Future<List<Note>> searchNotes(Database db, String title) async {
final rows = await db.query(
'notes',
where: 'title = ?',
whereArgs: [title],
);
return rows.map(Note.fromMap).toList();
}A database lets you change one row without touching the others. It also gives you a versioned schema, so a later app release can add columns for existing installs.
Images and downloads
Store the bytes as files in the documents or cache directory. Store the file path, plus any searchable information such as a caption, in the database. Putting large binary data into SQLite rows makes the database file big and slows queries that do not even need the image.
Choose the directory by lifetime:
- Documents directory for data the user would be upset to lose.
- Cache or temporary directory for data you can download or compute again. The operating system may clear it.
Combining options
Most apps split data by purpose. A typical note-taking app might look like this:
| Data | Storage | Reason |
|---|---|---|
| Theme and language | `shared_preferences` | Small, read at startup |
| Auth token | `flutter_secure_storage` | Secret |
| Notes (title, body, pinned) | SQLite | Many records, search and edit |
| Attached images | Files, with the path saved in SQLite | Large binary data |
| Exported backup | JSON file | One document, written once |
Splitting data this way keeps each store small and fits it to how the data is used.
Common mistakes
- Putting secrets in preferences. The value is stored unencrypted. Use secure storage for anything that grants access to an account.
- Using preferences as a database. Encoding a list as one JSON string in a preference works for a while. It fails when the list is large, because every change rewrites the entire value.
- Starting with files, then adding search. If you find yourself loading a whole file to look for one item, you have outgrown it.
- Storing large blobs in SQLite. Keep binary data in files and store the path.
- Treating the cache directory as permanent. The operating system can delete it at any time.
- Assuming secure storage is a general store. It is meant for small values. It is also slower than preferences, so do not use it for settings you read often.
- Skipping migrations. If you chose SQLite, plan for schema changes from version 1 by setting a
versionand usingonUpgrade.
Think about change
The first choice is not always final. A good way to keep it reversible is to hide storage behind a repository class, as covered in the earlier chapter. The rest of the app then calls loadNotes() or saveToken() and does not know whether a file or a database sits behind it. If a JSON file stops being enough, you replace the repository's internals with SQLite and move the existing data across once.
Plan the move before you need it. Read from the old store, write to the new one, and only then delete the old data. If the migration fails halfway, the user should still have the original.
When none of these fit
Some needs go beyond this chapter's four options.
- Data that must sync across devices needs a backend. Local storage can still act as a cache so the app works offline.
- Type-safe queries and generated code are available through
drift, which sits on top of SQLite. - Embedded NoSQL or object stores suit data that is naturally document-shaped and has little relational structure.
These tools solve different problems from the ones above. Add them when a concrete need appears, not by default.
Summary checklist
Before you commit to a storage option, check:
- Is the data secret? If yes, use secure storage and keep the value small.
- Is it a handful of simple values? Use preferences.
- Is it a large blob or a single document? Use a file in the right directory.
- Do you need search, sorting or single-row updates? Use SQLite.
- Will the data outgrow its first home? Put a repository in front.
Exercise
You are building a recipe app. It has (a) a "metric or imperial units" setting, (b) a refresh token for the user's account, (c) 5,000 saved recipes the user can search by ingredient, and (d) a photo for each recipe. Choose a storage option for each item and give one reason for each.
Show answer
(a) sharedpreferences, because it is one small value read at startup. (b) fluttersecure_storage, because a refresh token is a credential and must be protected by the platform keystore. (c) SQLite with sqflite, because there are thousands of records that need searching and single-row edits. (d) Files in the documents directory, with the file path stored in the recipes table, because photos are large binary data that would bloat the database.
Exercise
A teammate stores the list of a user's 2,000 favorite items as one JSON string in shared_preferences. Name two problems with this and say what you would use instead.
Show answer
Preferences are loaded into memory as a whole, so a large value slows reads, and every change rewrites the entire string. There is also no way to search or update a single item. Use SQLite if the user needs to search or edit items, or a JSON file if the list is always loaded and saved as a whole. Either choice should sit behind a repository.