On this page14 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What SharedPreferences Is For
  5. 2. Adding the Package
  6. 3. Saving and Reading
  7. Code Examples
  8. Common Beginner Mistakes
  9. Best Practices
  10. Mini Challenge
  11. Practice Questions
  12. Practice Answers
  13. Key Takeaways
  14. Full Code (Copy-Paste Reference)

Lecture 006: Saving Simple Data With SharedPreferences

Category3: SharedPreferences
Lecture006 of 008
Estimated video length12 min
TargetFlutter 3.44 · Dart 3.12 · shared_preferences 2.5
LevelBeginner

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_preferences package
  • Save values with setInt, setString, setBool, setDouble
  • Read them back with getInt, getString… and handle null
  • 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 forNot for
settings: theme, language, "seen onboarding"lists of notes, users or products
a username, a high score, a counterlarge 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

bash
flutter pub add shared_preferences
dart
import '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:

dart
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)
TypeSaveRead
intsetInt(key, v)getInt(key)
doublesetDouble(key, v)getDouble(key)
boolsetBool(key, v)getBool(key)
StringsetString(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 ??:

dart
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

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

dart
await prefs.setString('theme_mode', 'dark');
prefs.getBool('theme_mode');
code
type 'String' is not a subtype of type 'bool?' in type cast

Read 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).
  • await your set… 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

  1. Name two things that suit SharedPreferences and one that doesn't.
  2. Why is SharedPreferences.getInstance() awaited?
  3. What does getString('city') return if it was never saved?
  4. How do you delete one saved value?
  5. You saved setInt('score', 10). What happens with getString('score')?

Practice Answers

  1. Suits: theme choice, a username, a counter. Doesn't suit: a list of notes or a password.
  2. It returns a Future: getting the stored data takes a moment.
  3. null.
  4. prefs.remove('key').
  5. It throws a type error. Read it with getInt.

Key Takeaways

  • SharedPreferences saves small key-value data that survives restarts.
  • await SharedPreferences.getInstance(), then set… / 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

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')),
          ],
        ),
      ),
    );
  }
}