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
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.
Recommended next exercise
- Flutter API Call with http: solved REST exercise
- Firebase Auth Login in Flutter: solved email/password exercise
- FutureBuilder in Flutter: solved exercise for loading states
- All Flutter exercises
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View the C book on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
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.