Challenge - 5 Problems
SharedPreferences Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
What is the output after saving and reading a value?
Consider this Flutter code snippet that saves a string to SharedPreferences and then reads it back. What will be printed in the console?
Flutter
final prefs = await SharedPreferences.getInstance(); await prefs.setString('username', 'Alice'); final name = prefs.getString('username'); print(name);
Attempts:
2 left
💡 Hint
Remember that setString stores the value and getString retrieves it by the same key.
✗ Incorrect
The code saves the string 'Alice' under the key 'username'. Then it reads it back with getString using the same key, so it prints 'Alice'.
❓ lifecycle
intermediate2:00remaining
When should you initialize SharedPreferences in a Flutter app?
In a Flutter app, when is the best time to call SharedPreferences.getInstance() to ensure data is ready for use?
Attempts:
2 left
💡 Hint
Think about when you want to load data once when the widget is created.
✗ Incorrect
Calling SharedPreferences.getInstance() in initState() ensures the preferences are loaded once when the widget starts, avoiding repeated calls in build().
🔧 Debug
advanced2:00remaining
Why does this code fail to save the value?
Look at this Flutter code snippet. Why does it not save the integer value as expected?
Flutter
void saveScore() async { final prefs = await SharedPreferences.getInstance(); prefs.setInt('score', 100); }
Attempts:
2 left
💡 Hint
Check how you handle asynchronous calls in Dart.
✗ Incorrect
SharedPreferences.getInstance() returns a Future, so you must await it to get the instance before calling setInt.
🧠 Conceptual
advanced2:00remaining
What happens if you try to read a non-existent key?
If you call prefs.getString('nonexistentKey') on SharedPreferences where the key was never saved, what will be the result?
Attempts:
2 left
💡 Hint
Think about how Dart handles missing keys in maps or similar APIs.
✗ Incorrect
SharedPreferences returns null when a key does not exist, so getString returns null if the key is missing.
expert
2:00remaining
How to update UI after SharedPreferences value changes?
You saved a value in SharedPreferences and want your Flutter widget to update immediately to show the new value. Which approach works best?
Attempts:
2 left
💡 Hint
Think about how Flutter widgets update when data changes.
✗ Incorrect
SharedPreferences does not notify widgets automatically. You must read the new value and call setState() to rebuild the widget with updated data.