tezvyn:

shared_preferences for Simple On-Device Storage

AI-drafted, machine-checkedSource: pub.devbeginner

shared_preferences is Flutter's go-to for simple on-device key-value storage, like a persistent dictionary for user settings. Use it to save a dark mode toggle or high score. Crucially, writes are not guaranteed, so don't use it for critical data.

WHY IT EXISTS: Apps often need to remember small pieces of data between launches, like user preferences (e.g., dark mode) or simple state (e.g., has the user seen the intro tour?). shared_preferences provides a simple, cross-platform API for this without needing a full database.

THE MENTAL MODEL: Think of shared_preferences as a small, persistent Map<String, dynamic> stored on the device. You give it a key (like 'darkModeEnabled') and a value (like true), and you can retrieve that value later, even after the app restarts. It's for simple data, not complex or critical information.

HOW IT WORKS: The plugin wraps the native platform's standard for simple data storage: NSUserDefaults on iOS/macOS and SharedPreferences (or the newer DataStore) on Android. When you call a set method (e.g., setInt), the plugin passes this data to the native layer to be written to disk asynchronously. This means the write operation happens in the background and your app doesn't wait for it to complete. Newer APIs like SharedPreferencesAsync make all calls asynchronous to avoid cache inconsistencies, while older APIs use a cache for faster synchronous reads after an initial load.

WHEN TO USE IT: Use it for storing simple, non-critical user preferences and application state. Examples include: saving a theme choice (light/dark), remembering a user's name for a welcome message, or storing a high score in a simple game. It's perfect for data that is convenient to remember but not catastrophic if lost.

WHEN NOT TO USE IT: Do not use shared_preferences for critical data. Because writes are asynchronous and not guaranteed to persist if the app is killed, it's unsuitable for anything that must be saved reliably. Avoid it for storing sensitive information, complex relational data, or large amounts of data. For those cases, use a more robust solution like a SQLite database (via sqflite) or secure storage (flutter_secure_storage).

ONE CANONICAL EXAMPLE: To save a user's choice to enable dark mode, you would first get an instance of the preferences, then use the setBool method with a unique key. For example: final SharedPreferences prefs = await SharedPreferences.getInstance(); followed by await prefs.setBool('darkMode', true);. To read this value back when the app starts, you would use the getBool method: final bool? isDarkMode = prefs.getBool('darkMode');.

Read the original → pub.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.