Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data
The Flutter news you actually need
No spam, ever. Unsubscribe in one click.
When building a Flutter app, one of the first decisions you make is where to store data. You reach for shared_preferences for simple key-value pairs, and it works—until it doesn’t. Suddenly, a user’s “unique device ID” appears on their brand new phone after a cloud restore, or sensitive data you thought was secure gets swept into a backup. The core issue isn’t the APIs themselves, but understanding the lifetime and backup behavior of the data you’re storing. Let’s move beyond the defaults and choose the right tool for the job.
The Per-Install vs. Per-User Trap
The critical distinction often overlooked is between per-install and per-user data.
- Per-Install Data: Should exist only for this specific installation of the app on this specific device. It should be wiped on uninstall and never travel to a new device via backup/restore. Examples: A generated device identifier for local sync, cached temporary files, or a first-launch flag.
- Per-User Data: Belongs to the user and should follow them across devices via backups. Examples: User settings, saved favorites, or a high score.
The classic mistake is storing a per-install device ID in SharedPreferences. On Android, SharedPreferences (NSUserDefaults on iOS) is often included in automatic cloud backups. When the user restores their new phone from a backup, your app’s “unique” ID comes along for the ride, potentially causing data corruption if your logic assumes IDs are device-bound.
Choosing Your Storage Strategy
Here’s a practical guide to Flutter’s persistent storage options, focusing on their backup behavior and lifetime.
1. SharedPreferences: For User Preferences Only
Use it strictly for per-user preferences. Assume it may be backed up.
import 'package:shared_preferences/shared_preferences.dart';
// Good for per-user data
Future<void> saveUserTheme(bool isDark) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('isDarkMode', isDark);
}
Do NOT use it for: Device IDs, temporary session data, or anything that must be unique per installation.
2. path_provider: Know Your Directories
This package gives you paths to various system directories. Their backup behavior is key.
import 'package:path_provider/path_provider.dart';
Future<Directory> getAppStorageDirectory() async {
// Application Documents Directory: Backed up on both iOS & Android.
// Use for per-user files you create (e.g., user documents).
Directory appDocDir = await getApplicationDocumentsDirectory();
// Application Support Directory (iOS) / App Data Directory (Android):
// Similar to Documents, often used for app support files.
Directory appSupportDir = await getApplicationSupportDirectory();
// Temporary Directory: Not backed up, may be cleared by the OS.
Directory tempDir = await getTemporaryDirectory();
// For a true per-install, non-backed-up location, we need to go deeper (see next section).
return appDocDir;
}
The crucial directory path_provider doesn’t expose directly is Android’s noBackupFilesDir. This is the gold standard for per-install data on Android.
3. Securing Data and Controlling Backup
For Sensitive Per-Install Data: Use flutter_secure_storage
This stores data in platform-specific secure enclaves (Keychain/Keystore). It’s excellent for tokens, passwords, and per-install IDs, as it’s not part of standard file backups.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
Future<String> getOrCreateInstallId() async {
const storage = FlutterSecureStorage();
String? installId = await storage.read(key: 'install_id');
if (installId == null) {
installId = 'id_${DateTime.now().millisecondsSinceEpoch}';
await storage.write(key: 'install_id', value: installId);
}
return installId;
}
For Non-Sensitive Per-Install Files: Access the No-Backup Directory
Since path_provider doesn’t give us the Android noBackupFilesDir, we need a small platform channel or a dedicated package. Here’s a concise method channel approach:
-
Android (
android/app/src/main/kotlin/.../MainActivity.kt):import androidx.annotation.NonNull import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity: FlutterActivity() { private val CHANNEL = "com.example.app/storage" override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> if (call.method == "getNoBackupDirectoryPath") { result.success(applicationContext.noBackupFilesDir?.absolutePath) } else { result.notImplemented() } } } } -
Flutter/Dart:
import 'dart:io'; import 'package:path_provider/path_provider.dart'; Future<File> getPerInstallFile(String filename) async { Directory directory; if (Platform.isAndroid) { // Use method channel to get noBackupFilesDir path const channel = MethodChannel('com.example.app/storage'); final String? path = await channel.invokeMethod('getNoBackupDirectoryPath'); directory = Directory(path!); } else { // On iOS, use the Application Support directory and mark files as excluded. directory = await getApplicationSupportDirectory(); } // Ensure the directory exists if (!await directory.exists()) { await directory.create(recursive: true); } final file = File('${directory.path}/$filename'); // On iOS, set the 'do not backup' attribute. if (Platform.isIOS && await file.exists()) { await file.writeAsBytes(await file.readAsBytes(), flush: true); // Setting the attribute often requires a platform channel or package like `file_attributes`. } return file; } Future<void> writeInstallSpecificData() async { final file = await getPerInstallFile('device_config.json'); await file.writeAsString('{"installId": "unique_local_id"}'); }
Best Practices Checklist
- Audit Your Storage: Review every place you write data. Classify it as per-user or per-install.
- Per-User Data: Use
SharedPreferencesor theApplicationDocumentsDirectory. Document that it backs up. - Per-Install Data: Use
flutter_secure_storagefor sensitive IDs or the AndroidnoBackupFilesDir(via method channel) for files. On iOS, store inApplicationSupportDirectoryand set theNSURLIsExcludedFromBackupKeyattribute. - Test Backups & Restores: This is non-negotiable. Install your app, write data, use system backup/restore (or Android ADB backup), and verify the behavior.
By understanding the lifecycle and backup semantics of your storage choices, you can prevent subtle, data-corrupting bugs and build more robust Flutter applications.
This blog is produced with the assistance of AI by a human editor. Learn more
Related Posts
Fixing Flutter TextField Issues: Preventing Input Lag, Lost Keystrokes, and Keyboard Glitches
Many Flutter developers struggle with common TextField issues like typing lag, lost keystrokes, or erratic keyboard behavior. This post will diagnose the root causes of these problems, including state management, TextEditingController misuse, and custom decorations, offering practical solutions for a smooth and reliable user input experience.
Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data
Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.
Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring
Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.