SharedPreferences in Flutter: solved exercise for local settings

SharedPreferences in Flutter: solved exercise

If you are looking for SharedPreferences in Flutter, this solved exercise gives you a practical implementation pattern you can reuse in real projects.

Problem statement

Build a screen with:

  • save local username
  • reload saved value on app start
  • show persisted value in UI

Flutter solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(const MaterialApp(home: PreferencesPage()));

class PreferencesPage extends StatefulWidget {
  const PreferencesPage({super.key});

  @override
  State<PreferencesPage> createState() => _PreferencesPageState();
}

class _PreferencesPageState extends State<PreferencesPage> {
  final ctrl = TextEditingController();
  String savedName = '';

  @override
  void initState() {
    super.initState();
    loadName();
  }

  Future<void> loadName() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() => savedName = prefs.getString('name') ?? '');
  }

  Future<void> saveName() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('name', ctrl.text.trim());
    await loadName();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('SharedPreferences')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(controller: ctrl, decoration: const InputDecoration(labelText: 'Name')),
            const SizedBox(height: 12),
            ElevatedButton(onPressed: saveName, child: const Text('Save')),
            const SizedBox(height: 16),
            Text('Saved: $savedName'),
          ],
        ),
      ),
    );
  }
}

Expected result

The stored value remains available after closing and reopening the app.

Common mistakes

  • Using SharedPreferences for complex structured data.
  • Ignoring async timing.
  • Saving unvalidated input values.

Practical use

Useful for onboarding flags, UI preferences, and small user settings.

Guided practice and next step

FAQ

Is SharedPreferences secure for sensitive data?

No. Use secure encrypted storage for sensitive values.

How much data should I store there?

Only small key-value settings, not large datasets.

When should I move to SQLite?

When you need structured queries and relational local data.