0
0
Fluttermobile~20 mins

SharedPreferences for key-value in Flutter - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
SharedPreferences Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
ui_behavior
intermediate
2: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);
AAlice
BThrows an exception
C'' (empty string)
Dnull
Attempts:
2 left
💡 Hint
Remember that setString stores the value and getString retrieves it by the same key.
lifecycle
intermediate
2: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?
AIn the main() function before runApp()
BAfter the widget is disposed
CInside the build() method of a widget
DIn the initState() method of a StatefulWidget
Attempts:
2 left
💡 Hint
Think about when you want to load data once when the widget is created.
🔧 Debug
advanced
2: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);
}
AThe key 'score' is reserved and cannot be used
BsetInt() does not exist in SharedPreferences
CSharedPreferences.getInstance() returns a Future, so it must be awaited
DThe method saveScore() must be synchronous
Attempts:
2 left
💡 Hint
Check how you handle asynchronous calls in Dart.
🧠 Conceptual
advanced
2: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?
AIt throws a KeyNotFoundException
BIt returns null
CIt returns an empty string ''
DIt returns the string 'null'
Attempts:
2 left
💡 Hint
Think about how Dart handles missing keys in maps or similar APIs.
navigation
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?
AUse setState() after reading the updated value from SharedPreferences
BRestart the app to reload SharedPreferences
CUse a StreamBuilder directly on SharedPreferences
DSharedPreferences automatically notifies widgets to rebuild
Attempts:
2 left
💡 Hint
Think about how Flutter widgets update when data changes.