0
0
Fluttermobile~20 mins

SharedPreferences for key-value in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Key-Value Storage
This screen lets the user save a text value using SharedPreferences and load it back to display.
Target UI
-------------------------
| Simple Key-Value Storage |
-------------------------
| Enter text:             |
| [______________]        |
|                         |
| [Save]   [Load]         |
|                         |
| Saved value:            |
| [____________________]  |
-------------------------
A TextField for user input
A Save button that stores the input text in SharedPreferences with key 'myKey'
A Load button that retrieves the stored text and shows it below
Display the saved value in a Text widget
Use proper async handling for SharedPreferences
UI should be simple and clear
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class KeyValueScreen extends StatefulWidget {
  @override
  State<KeyValueScreen> createState() => _KeyValueScreenState();
}

class _KeyValueScreenState extends State<KeyValueScreen> {
  final TextEditingController _controller = TextEditingController();
  String _savedValue = '';

  // TODO: Add save and load methods here

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Simple Key-Value Storage')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Enter text:'),
            TextField(controller: _controller),
            SizedBox(height: 20),
            Row(
              children: [
                ElevatedButton(
                  onPressed: () {
                    // TODO: Implement save
                  },
                  child: Text('Save'),
                ),
                SizedBox(width: 10),
                ElevatedButton(
                  onPressed: () {
                    // TODO: Implement load
                  },
                  child: Text('Load'),
                ),
              ],
            ),
            SizedBox(height: 30),
            Text('Saved value:'),
            SizedBox(height: 10),
            Text(_savedValue, style: TextStyle(fontSize: 18, color: Colors.blue)),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class KeyValueScreen extends StatefulWidget {
  @override
  State<KeyValueScreen> createState() => _KeyValueScreenState();
}

class _KeyValueScreenState extends State<KeyValueScreen> {
  final TextEditingController _controller = TextEditingController();
  String _savedValue = '';

  Future<void> _saveValue() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('myKey', _controller.text);
  }

  Future<void> _loadValue() async {
    final prefs = await SharedPreferences.getInstance();
    final value = prefs.getString('myKey') ?? '';
    setState(() {
      _savedValue = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Simple Key-Value Storage')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Enter text:'),
            TextField(controller: _controller),
            SizedBox(height: 20),
            Row(
              children: [
                ElevatedButton(
                  onPressed: _saveValue,
                  child: Text('Save'),
                ),
                SizedBox(width: 10),
                ElevatedButton(
                  onPressed: _loadValue,
                  child: Text('Load'),
                ),
              ],
            ),
            SizedBox(height: 30),
            Text('Saved value:'),
            SizedBox(height: 10),
            Text(_savedValue, style: TextStyle(fontSize: 18, color: Colors.blue)),
          ],
        ),
      ),
    );
  }
}

We use the shared_preferences package to store and retrieve simple key-value data.

The _saveValue method gets the SharedPreferences instance asynchronously and saves the text from the input field under the key myKey.

The _loadValue method retrieves the stored string for myKey and updates the state to show it on screen.

Buttons call these methods on press. This keeps the UI responsive and data persistent across app restarts.

Final Result
Completed Screen
-------------------------
| Simple Key-Value Storage |
-------------------------
| Enter text:             |
| [Hello Flutter!]        |
|                         |
| [Save]   [Load]         |
|                         |
| Saved value:            |
| Hello Flutter!          |
-------------------------
User types text in the input field.
Tapping 'Save' stores the text in SharedPreferences.
Tapping 'Load' retrieves the saved text and displays it below.
Saved value updates immediately after loading.
Stretch Goal
Add a Clear button that removes the saved key-value from SharedPreferences and clears the displayed saved value.
💡 Hint
Use SharedPreferences.remove('myKey') method and update the state to clear _savedValue.