On this page14 sections
Lecture 006: Saving Simple Data With SharedPreferences
| Category | 3: SharedPreferences |
| Lecture | 006 of 008 |
| Estimated video length | 12 min |
| Target | Flutter 3.44 · Dart 3.12 · shared_preferences 2.5 |
| Level | Beginner |
Close My Notes, open it again, and dark mode is gone, because everything in memory disappears when the app closes. SharedPreferences saves small pieces of data on the phone (a setting, a name, a counter) so they're still there next time.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Dart Future, async and await (Dart Basic 056), and StatefulWidget with initState.
Connection With Previous Lectures
This lecture steps away from the theme to learn SharedPreferences on its own, with a tiny "visit counter" screen. Lecture 007 brings it back to the theme.
Learning Objectives
- Know what SharedPreferences is for, and what it isn't for
- Add the
shared_preferencespackage - Save values with
setInt,setString,setBool,setDouble - Read them back with
getInt,getString… and handlenull - Remove values with
remove
1. What SharedPreferences Is For
SharedPreferences stores small key-value pairs on the device (it uses NSUserDefaults on
iOS and SharedPreferences on Android).
| Good for | Not for |
|---|---|
| settings: theme, language, "seen onboarding" | lists of notes, users or products |
| a username, a high score, a counter | large data or files |
simple flags (true/false) | passwords or tokens (not encrypted) |
For real data, use a database (Hive, Sqflite, Firebase); for secrets, use secure storage.
2. Adding the Package
flutter pub add shared_preferencesimport 'package:shared_preferences/shared_preferences.dart';3. Saving and Reading
Get the instance (it's async), then use set… and get… with a key, a name you choose:
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('visits', 3);
await prefs.setString('name', 'Ayesha');
await prefs.setBool('dark', true);
final visits = prefs.getInt('visits'); // 3
final name = prefs.getString('name'); // Ayesha
final missing = prefs.getString('city'); // null (never saved)| Type | Save | Read |
|---|---|---|
int | setInt(key, v) | getInt(key) |
double | setDouble(key, v) | getDouble(key) |
bool | setBool(key, v) | getBool(key) |
String | setString(key, v) | getString(key) |
List<String> | setStringList(key, v) | getStringList(key) |
Every get… returns a nullable value, because the key might never have been saved. Give a
default with ??:
final visits = prefs.getInt('visits') ?? 0;set… returns a Future, so await it. remove(key) deletes one value.
Code Examples
Example 1: A Visit Counter That Remembers Your Name
lib/main.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MaterialApp(home: VisitsScreen()));
}
class VisitsScreen extends StatefulWidget {
const VisitsScreen({super.key});
@override
State<VisitsScreen> createState() => _VisitsScreenState();
}
class _VisitsScreenState extends State<VisitsScreen> {
int _visits = 0;
String _name = '';
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final prefs = await SharedPreferences.getInstance();
final visits = (prefs.getInt('visits') ?? 0) + 1;
await prefs.setInt('visits', visits);
setState(() {
_visits = visits;
_name = prefs.getString('name') ?? 'Guest';
});
}
Future<void> _saveName(String name) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('name', name);
setState(() => _name = name);
}
Future<void> _reset() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('visits');
await prefs.remove('name');
setState(() {
_visits = 0;
_name = 'Guest';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('SharedPreferences')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Hello, $_name!', style: Theme.of(context).textTheme.headlineSmall),
Text('You have opened this screen $_visits times.'),
const SizedBox(height: 16),
TextField(
decoration: const InputDecoration(labelText: 'Your name'),
onSubmitted: _saveName,
),
const SizedBox(height: 16),
OutlinedButton(onPressed: _reset, child: const Text('Reset')),
],
),
),
);
}
}Try it: run the app (it says opened 1 times), type a name and press Enter. Stop the app completely and run it again: it greets you by name and the count has gone up.
initState can't be async, so it calls _load(), which is. The screen shows 0 and Guest
for a moment, then updates when the saved values arrive.
Tested: starting with visits = 2 saved, the screen showed opened 3 times, saved the typed
name as 'Ayesha', and Reset removed the visits key.
Common Beginner Mistakes
1. Reading with the wrong type
await prefs.setString('theme_mode', 'dark');
prefs.getBool('theme_mode');type 'String' is not a subtype of type 'bool?' in type castRead a key with the same type you saved it with.
2. Ignoring null: int visits = prefs.getInt('visits'); won't compile, because the value is
int?. The first time the app runs, nothing is saved yet. Use ?? 0.
3. Typos in keys: saving 'visits' and reading 'visit' gives null with no error. Keep
keys in constants (static const _visitsKey = 'visits';).
4. Storing big or secret data: SharedPreferences isn't a database and isn't encrypted.
Best Practices
- Use clear, constant keys.
- Always give a default when reading (
?? defaultValue). awaityourset…calls so you know the save has finished.- Keep it to small settings; anything bigger belongs in a database.
Mini Challenge
Save a bool called 'seen_welcome'. The first time the app opens, show a "Welcome!" Text;
after that, hide it.
Practice Questions
- Name two things that suit SharedPreferences and one that doesn't.
- Why is
SharedPreferences.getInstance()awaited? - What does
getString('city')return if it was never saved? - How do you delete one saved value?
- You saved
setInt('score', 10). What happens withgetString('score')?
Practice Answers
- Suits: theme choice, a username, a counter. Doesn't suit: a list of notes or a password.
- It returns a
Future: getting the stored data takes a moment. null.prefs.remove('key').- It throws a type error. Read it with
getInt.
Key Takeaways
- SharedPreferences saves small key-value data that survives restarts.
await SharedPreferences.getInstance(), thenset…/get…with a key.get…returns nullable values; use??for defaults.- Same key, same type, every time.
- Next: saving the theme choice so My Notes remembers it.
Full Code (Copy-Paste Reference)
This lecture is a standalone demo, separate from the My Notes app: one file.
lib/main.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MaterialApp(home: VisitsScreen()));
}
class VisitsScreen extends StatefulWidget {
const VisitsScreen({super.key});
@override
State<VisitsScreen> createState() => _VisitsScreenState();
}
class _VisitsScreenState extends State<VisitsScreen> {
int _visits = 0;
String _name = '';
@override
void initState() {
super.initState();
// initState can't be async itself, so it kicks off an async helper.
_load();
}
Future<void> _load() async {
final prefs = await SharedPreferences.getInstance();
final visits = (prefs.getInt('visits') ?? 0) + 1; // ?? 0 covers the very first run
await prefs.setInt('visits', visits);
setState(() {
_visits = visits;
_name = prefs.getString('name') ?? 'Guest';
});
}
Future<void> _saveName(String name) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('name', name);
setState(() => _name = name);
}
Future<void> _reset() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('visits');
await prefs.remove('name');
setState(() {
_visits = 0;
_name = 'Guest';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('SharedPreferences')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Hello, $_name!', style: Theme.of(context).textTheme.headlineSmall),
Text('You have opened this screen $_visits times.'),
const SizedBox(height: 16),
TextField(
decoration: const InputDecoration(labelText: 'Your name'),
onSubmitted: _saveName,
),
const SizedBox(height: 16),
OutlinedButton(onPressed: _reset, child: const Text('Reset')),
],
),
),
);
}
}