When to use shared_preferences and its primary limitations?
This tests whether you know appropriate local persistence tiers. A strong answer names simple primitives like flags or tokens, notes async disk writes, and warns against large blobs, relational data, or secrets.
WHAT THIS TESTS: Your judgment in selecting local persistence layers. The interviewer wants to see that you understand shared_preferences is a lightweight key-value store and that you can articulate exactly where it stops being useful. Senior engineers should map data characteristics to storage backends without defaulting to the easiest option.
A GOOD ANSWER COVERS: Four things in order. First, ideal use cases: small primitive values like feature flags, onboarding completion booleans, user preference strings, or lightweight authentication tokens. Second, the API model: asynchronous get and set operations backed by an in-memory cache that flushes to disk, which means you must await writes and handle null defaults. Third, concrete limitations: no querying or indexing, no support for nested objects without manual serialization, poor performance for large payloads or high-frequency writes because it rewrites the entire file, and no built-in encryption so it is unsafe for passwords or PII. Fourth, alternatives: SQLite or Hive for relational or structured data, path_provider with dart:io for large files, and flutter_secure_storage for secrets.
COMMON WRONG ANSWERS: Three red flags. One, calling it synchronous. Two, suggesting it for caching network images or large JSON blobs without mentioning size constraints. Three, claiming it is secure or encrypted by default. Another subtle trap is forgetting to mention that it stores data as simple key-value pairs and therefore cannot handle complex data models without extra work.
LIKELY FOLLOW-UPS: The interviewer may ask how you would store a complex object, which should lead to jsonEncode and jsonDecode with a String value. They might ask about testing, where you should mention SharedPreferences.setMockInitialValues. They could also ask about concurrent writes across isolates or platform-specific backing stores, which on Android uses SharedPreferences and on iOS uses NSUserDefaults.
ONE CONCRETE EXAMPLE: Suppose you need to persist whether a user has seen a tutorial. A boolean flag named hasSeenTutorial is perfect for shared_preferences because it is tiny, read once at startup, and updated once. If you later need to store the user's entire offline message history with search, shared_preferences would be the wrong tool because you would load a massive string into memory on every read and rewrite the entire file on every new message. You would migrate to SQLite with proper indexing.
Read the original → docs.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.