Bird
Raised Fist0
Fluttermobile~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using SharedPreferences in a Flutter app?
easy
A. To save small key-value data that persists after the app closes
B. To create complex database tables
C. To design the app's user interface
D. To handle network requests

Solution

  1. Step 1: Understand SharedPreferences role

    SharedPreferences is designed to store simple data like settings or flags in key-value pairs.
  2. Step 2: Compare with other options

    Options A, B, and C relate to databases, UI, and networking, which are not the purpose of SharedPreferences.
  3. Final Answer:

    To save small key-value data that persists after the app closes -> Option A
  4. Quick Check:

    SharedPreferences = persistent small key-value storage [OK]
Hint: Remember: SharedPreferences stores simple data persistently [OK]
Common Mistakes:
  • Confusing SharedPreferences with databases
  • Thinking it manages UI or network
  • Assuming it stores large files
2. Which of the following is the correct way to save a boolean value true with key isLoggedIn using SharedPreferences in Flutter?
easy
A. prefs.putBool('isLoggedIn', true);
B. prefs.saveBool('isLoggedIn', true);
C. prefs.storeBool('isLoggedIn', true);
D. prefs.setBool('isLoggedIn', true);

Solution

  1. Step 1: Recall SharedPreferences method names

    The correct method to save a boolean is setBool.
  2. Step 2: Check method correctness

    Options A, B, and D use incorrect method names that do not exist in SharedPreferences API.
  3. Final Answer:

    prefs.setBool('isLoggedIn', true); -> Option D
  4. Quick Check:

    Save boolean = setBool [OK]
Hint: Use setBool to save booleans in SharedPreferences [OK]
Common Mistakes:
  • Using incorrect method names like saveBool or putBool
  • Forgetting to await async calls
  • Confusing setBool with setString
3. Given the following Flutter code snippet, what will be printed?
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('counter', 5);
int count = prefs.getInt('counter') ?? 0;
print(count);
medium
A. 0
B. null
C. 5
D. Error

Solution

  1. Step 1: Analyze saving the value

    The code saves integer 5 with key 'counter' using setInt.
  2. Step 2: Analyze reading the value

    It reads the value with getInt. Since 'counter' exists, it returns 5, not the default 0.
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    Saved int 5, getInt returns 5 [OK]
Hint: getInt returns saved value or default if missing [OK]
Common Mistakes:
  • Assuming getInt returns null instead of default
  • Confusing setInt with setString
  • Forgetting to await setInt
4. What is wrong with this Flutter code that tries to save a string in SharedPreferences?
final prefs = SharedPreferences.getInstance();
prefs.setString('username', 'Alice');
medium
A. setString method does not exist
B. Missing await before getInstance()
C. Key 'username' cannot be a string
D. Cannot save strings in SharedPreferences

Solution

  1. Step 1: Check getInstance usage

    getInstance() returns a Future, so it must be awaited or handled asynchronously.
  2. Step 2: Check setString call

    Calling setString on a Future object (not the SharedPreferences instance) causes error.
  3. Final Answer:

    Missing await before getInstance() -> Option B
  4. Quick Check:

    Always await SharedPreferences.getInstance() [OK]
Hint: Always await getInstance() before using prefs [OK]
Common Mistakes:
  • Not awaiting getInstance()
  • Calling setString on Future instead of instance
  • Confusing async calls with sync
5. You want to save a user's theme preference as a string ('light' or 'dark') and a flag if notifications are enabled (boolean). Which of the following code snippets correctly saves both values using SharedPreferences in Flutter?
hard
A. final prefs = await SharedPreferences.getInstance(); await prefs.setString('theme', 'dark'); await prefs.setBool('notifications', true);
B. final prefs = SharedPreferences.getInstance(); prefs.setString('theme', 'dark'); prefs.setBool('notifications', true);
C. final prefs = await SharedPreferences.getInstance(); prefs.setInt('theme', 'dark'); prefs.setBool('notifications', true);
D. final prefs = await SharedPreferences.getInstance(); await prefs.setInt('theme', 1); await prefs.setBool('notifications', 'true');

Solution

  1. Step 1: Check async usage

    SharedPreferences.getInstance() must be awaited to get the instance before use.
  2. Step 2: Check method calls and types

    setString saves the theme string correctly; setBool saves the boolean flag correctly. Both use await for async calls.
  3. Step 3: Identify errors in other options

    final prefs = SharedPreferences.getInstance(); prefs.setString('theme', 'dark'); prefs.setBool('notifications', true); misses await on getInstance and set methods; final prefs = await SharedPreferences.getInstance(); prefs.setInt('theme', 'dark'); prefs.setBool('notifications', true); uses setInt('theme', 'dark') causing type error ('dark' not int); final prefs = await SharedPreferences.getInstance(); await prefs.setInt('theme', 1); await prefs.setBool('notifications', 'true'); uses wrong types (setInt for string, boolean as string).
  4. Final Answer:

    final prefs = await SharedPreferences.getInstance(); await prefs.setString('theme', 'dark'); await prefs.setBool('notifications', true); -> Option A
  5. Quick Check:

    Await getInstance and setX methods with correct types [OK]
Hint: Await all async SharedPreferences calls with correct types [OK]
Common Mistakes:
  • Not awaiting async calls
  • Using wrong data types for values
  • Saving booleans as strings
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard