SharedPreferences in Flutter: solved exercise for local settings

  2 minutes

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

Build a screen with:

  • save local username
  • reload saved value on app start
  • show persisted value in UI
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'),
          ],
        ),
      ),
    );
  }
}

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

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

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

No. Use secure encrypted storage for sensitive values.

Only small key-value settings, not large datasets.

When you need structured queries and relational local data.