How to Access and Use Shared Preferences in Flutter: Complete Guide
The shared_preferences plugin provides a persistent key-value store for Flutter apps by bridging Dart code to native platform storage via platform channels, storing data in XML files on Android, NSUserDefaults on iOS/macOS, and localStorage on the web.
The shared_preferences plugin is the standard solution for lightweight data persistence in the Flutter ecosystem. According to the flutter/flutter source code and its associated plugin implementations, this library abstracts platform-specific storage mechanisms into a unified Dart API. Understanding the underlying architecture helps developers debug storage issues and optimize read/write operations across Android, iOS, macOS, and web platforms.
How Shared Preferences Flutter Works Under the Hood
The plugin follows Flutter's platform-channel architecture, separating the public Dart interface from native implementations that handle actual file I/O operations.
Dart API Layer
The public API lives in shared_preferences.dart within the shared_preferences package. When you invoke SharedPreferences.getInstance(), the Dart layer obtains a singleton instance that proxies all calls through the SharedPreferencesPlatform interface. Methods like getInt(), setString(), and remove() serialize data into platform messages before transmitting to the native side.
Platform Channel Architecture
The abstraction is defined in shared_preferences_platform_interface.dart, which declares abstract methods that every platform implementation must satisfy. This interface ensures consistent behavior whether the app runs on mobile, desktop, or web. Each method signature corresponds to a specific storage operation that native code executes asynchronously.
Android Implementation
On Android, the plugin utilizes android.content.SharedPreferences to read and write a private XML file. The implementation in shared_preferences_android.dart targets the file path /data/data/<package>/shared_prefs/<package>_preferences.xml. Data persists as key-value pairs in this XML structure, accessible only to the application package that created it.
iOS and macOS Implementation
For Apple platforms, the plugin wraps NSUserDefaults as implemented in shared_preferences_ios.dart. Data stores in the app’s sandboxed preferences plist within the device’s library directory. This native API automatically handles synchronization and provides efficient lookup for small configuration values.
Web Implementation
The web implementation in shared_preferences_web.dart persists data using the browser’s window.localStorage. Unlike mobile platforms that use files, web storage saves key-value pairs directly in the browser with a default quota of approximately 5-10 MB per origin.
Plugin Registration
When a Flutter app starts, the GeneratedPluginRegistrant (generated by the Flutter engine in packages/flutter_tools/lib/src/flutter_plugins.dart) registers SharedPreferencesPlugin with the engine. This registration binds the Dart method channel to the correct native implementation before any user code executes.
Accessing Shared Preferences in Flutter: Step-by-Step Implementation
To begin using shared preferences flutter, add the dependency to your pubspec.yaml:
dependencies:
shared_preferences: ^2.2.2
Then import the package and implement read/write operations:
import 'package:shared_preferences/shared_preferences.dart';
Future<void> demoSharedPreferences() async {
// Obtain the singleton instance
final prefs = await SharedPreferences.getInstance();
// Write values
await prefs.setInt('launchCount', 5);
await prefs.setString('username', 'flutter_dev');
await prefs.setBool('darkMode', true);
// Read values (provide a default if the key is absent)
final int launchCount = prefs.getInt('launchCount') ?? 0;
final String? username = prefs.getString('username');
final bool darkMode = prefs.getBool('darkMode') ?? false;
// Remove a single key
await prefs.remove('username');
// Clear all preferences (use with caution)
// await prefs.clear();
print('Launches: $launchCount, User: $username, Dark mode: $darkMode');
}
Always call await SharedPreferences.getInstance() before performing operations, as the plugin initializes the native storage connection asynchronously.
Where Flutter Stores Shared Preferences Data
Each platform stores the underlying file in a distinct location:
- Android: XML file at
/data/data/<package_name>/shared_prefs/<package_name>_preferences.xml - iOS/macOS: Binary plist in the app container's
Library/Preferences/<bundle_identifier>.plist - Web: Browser's
localStorageobject, inspectable via DevTools Application tab
You can access these files during debugging using Android Studio's Device File Explorer or Xcode's device management tools, but production apps should never rely on direct file manipulation outside the plugin's API.
Summary
- The
shared_preferencesplugin abstracts native storage through Flutter's platform channel system. - Android implementations write to private XML files via
android.content.SharedPreferences. - iOS and macOS use
NSUserDefaultswith plist storage in the app sandbox. - Web platforms utilize
window.localStoragefor persistence. - Always await
SharedPreferences.getInstance()before calling get or set methods. - Data persists across app launches but is not encrypted; avoid storing sensitive information like passwords or tokens.
Frequently Asked Questions
Where is the shared preferences file located in Flutter?
On Android, the file resides at /data/data/<package>/shared_prefs/<package>_preferences.xml as an XML document. On iOS and macOS, data stores in the app's Library/Preferences/ directory as a plist file managed by NSUserDefaults. Web implementations use the browser's localStorage instead of physical files.
How do I clear all shared preferences in Flutter?
Call await prefs.clear() on your SharedPreferences instance. This removes every key-value pair from the underlying storage file or NSUserDefaults domain. Use this method cautiously in production, as it deletes all persisted user settings without recovery options.
Can I access shared preferences flutter from native code?
Yes, because the plugin uses standard native APIs. On Android, you can access the same XML file directly using getSharedPreferences() in Kotlin or Java. On iOS, you can read the same keys using [[NSUserDefaults standardUserDefaults] in Objective-C or UserDefaults.standard in Swift, provided you use the correct app group or suite name.
Is shared_preferences secure for sensitive data?
No, shared_preferences is not encrypted and stores data in plain text readable by rooted devices or users with filesystem access. For sensitive information like authentication tokens or personal data, use the flutter_secure_storage plugin or platform-specific Keychain/Keystore APIs instead.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →