Sub topic 2
Saving settings with shared_preferences
This chapter assumes you can write Dart classes with null safety, use async and await, add a package to pubspec.yaml, and build a basic Flutter app with state. You will learn how shared_preferences works, how to read and write each supported type, and the mistakes that most often cause bugs.
What shared_preferences is
shared_preferences is a Flutter plugin that stores small pieces of data as key-value pairs. A key is a string such as 'dark_mode'. A value is one of a few simple types. The data survives app restarts, so the plugin suits user settings such as theme choice, language, onboarding state and the last selected tab.
Each platform uses its own native mechanism underneath:
| Platform | Backing store |
|---|---|
| Android | SharedPreferences (an XML file in the app's private data) |
| iOS and macOS | NSUserDefaults |
| Linux, Windows | A JSON file in the app's data directory |
| Web | Browser localStorage |
You do not need to know these details to use the plugin. They matter for one reason: the plugin is built for small, simple data. It is not a database and it does not encrypt anything.
Add the package from the command line:
flutter pub add shared_preferencesSupported types
A preference value can be one of these Dart types:
| Type | Write | Read |
|---|---|---|
| `bool` | `setBool` | `getBool` |
| `int` | `setInt` | `getInt` |
| `double` | `setDouble` | `getDouble` |
| `String` | `setString` | `getString` |
| `List<String>` | `setStringList` | `getStringList` |
Nothing else is supported directly. To store a DateTime, an enum or a model object, you convert it to one of these types first. Chapter sections on serialization cover the general approach. For preferences, the usual choice is a string, such as an ISO 8601 date or an enum name.
Writing and reading a value
The example below saves a boolean and reads it back. The read falls back to false when the key has never been written.
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;
}Three details in this code matter.
SharedPreferences.getInstance()is asynchronous. It loads the stored data the first time you call it and returns the same cached instance afterwards.setBoolreturns aFuture. Awaiting it means the write has been handed to the platform before your code continues.getBoolreturnsbool?. If the key does not exist, the result isnull, and the?? falsesupplies a default.
What happens on a read
Understanding the cache explains most surprises. The diagram shows the lifecycle of one preference value.
The plugin loads everything once, then answers reads from memory. This is fast, and it is why preferences are a poor place for large data: every value is loaded into memory at startup.
Handling missing keys and removing data
Always decide what a missing key means. A null result is not an error. It tells you the user has not chosen a value yet.
import 'package:shared_preferences/shared_preferences.dart';
Future<void> demo() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', 'ana');
await prefs.setInt('launch_count', 3);
await prefs.setStringList('recent_searches', ['flutter', 'dart']);
final name = prefs.getString('username'); // 'ana'
final missing = prefs.getString('nickname'); // null
final hasName = prefs.containsKey('username'); // true
await prefs.remove('username');
print('$name $missing $hasName');
// Removes every key. Use with care.
await prefs.clear();
}remove deletes one key. clear deletes everything the app has stored in preferences, including values written by unrelated features, so avoid it outside of a "reset app" or "log out" flow.
Common errors
Type mismatch on read
If you wrote a key with setInt and read it with getString, the plugin throws a type error. Keys are untyped in storage, so the type you read must match the type you wrote. This often happens after a refactor that changes a setting from int to String while old installs still hold the old type.
A defensive reader handles it:
import 'package:shared_preferences/shared_preferences.dart';
int readLaunchCount(SharedPreferences prefs) {
final raw = prefs.get('launch_count');
if (raw is int) return raw;
if (raw is String) return int.tryParse(raw) ?? 0;
return 0;
}prefs.get returns the value as Object? without committing to a type, so you can check it yourself.
Forgetting to initialize the binding
If you read preferences before runApp, for example to pick an initial theme, Flutter's binding must exist first:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
final dark = prefs.getBool('dark_mode') ?? false;
runApp(MyApp(initialDark: dark));
}
class MyApp extends StatelessWidget {
const MyApp({super.key, required this.initialDark});
final bool initialDark;
@override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: initialDark ? ThemeMode.dark : ThemeMode.light,
home: const Scaffold(body: Center(child: Text('Hello'))),
);
}
}Loading the value before runApp avoids a flash of the wrong theme on startup.
Typos in key strings
Repeating 'dark_mode' as a literal in several files invites typos that silently return null. Collect keys in one place:
abstract final class PrefKeys {
static const darkMode = 'dark_mode';
static const launchCount = 'launch_count';
static const recentSearches = 'recent_searches';
}Storing sensitive data
Preferences are stored unencrypted in the app's data area. On a rooted or jailbroken device, or in a device backup, anyone can read them. Do not store passwords, access tokens or personal data here. The secure storage chapter covers the alternative.
Storing too much
Because the whole store loads into memory and is rewritten as a unit on some platforms, large lists or serialized objects slow startup and risk data loss on a failed write. As a rule of thumb, keep preferences to a handful of small values, in total well under a few hundred kilobytes. If you find yourself writing JSON blobs into a string key, move to a file or a database.
Testing code that uses preferences
You do not need a device to test preference code. The package provides setMockInitialValues, which replaces the platform store with an in-memory map.
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('loads saved dark mode value', () async {
SharedPreferences.setMockInitialValues({'dark_mode': true});
expect(await loadDarkMode(), isTrue);
});
test('defaults to false when nothing is stored', () async {
SharedPreferences.setMockInitialValues({});
expect(await loadDarkMode(), isFalse);
});
}This test uses the loadDarkMode function defined earlier in the chapter, so import the file that contains it. Call setMockInitialValues at the start of each test so data from one test cannot leak into the next.
Decision criteria
Use shared_preferences when the data is:
- small, such as flags, short strings and counters,
- a simple type from the supported list,
- non-sensitive,
- read by key and never queried by content.
Move to another option when you need secrecy (secure storage), larger or structured documents (files), or filtering and sorting (SQLite). Later chapters walk through each of these.
Exercises
Exercise
A user's app wrote launch_count with setInt in version 1. In version 2, a developer changed the code to read it with getString. What happens on an existing install, and how can you read the value safely?
Show answer
The read throws a type error because the stored value is an int. Read it with prefs.get('launch_count'), which returns Object?, check the runtime type with is, and convert or default as needed.
Exercise
Why is it a bad idea to save a list of 5,000 serialized notes as a single JSON string in shared_preferences?
Show answer
The plugin loads all stored values into memory at startup and may rewrite them as a unit, so a large value slows launch and raises the risk of losing data on a failed write. A file or a SQLite database is the better fit.
Exercise
Write a function incrementLaunchCount that reads launch_count (default 0), adds one, saves it, and returns the new value.
Show answer
Future<int> incrementLaunchCount() async { final prefs = await SharedPreferences.getInstance(); final next = (prefs.getInt('launchcount') ?? 0) + 1; await prefs.setInt('launchcount', next); return next; }