If you’re developing a mobile application with Flutter or Dart, understanding how to delete data locally is essential—especially for apps with offline functionality. Whether you’re using shared preferences, local database (like SQLite), or temporary storage, Dart provides efficient ways to manage and delete local data. This guide walks you through a complete example of deleting data from local storage using the shared_preferences
package.

Why Delete Local Data?
Deleting local data is helpful when:
- Users log out of an app
- You want to reset the app to default state
- Cache needs to be cleared to free up space
- Security requires data to be removed from the device
Best Practice: Use shared_preferences
for Key-Value Storage
One of the simplest methods for storing and deleting user data is with the shared_preferences
plugin. This package allows you to store data as key-value pairs and manage it easily.
Step-by-Step Implementation
1. Add Dependencies
In your pubspec.yaml
file:
dependencies: flutter: sdk: flutter shared_preferences: ^2.2.2
Run flutter pub get
to install the package.
2. Storage Service Class (SharedPreferences)
import 'package:shared_preferences/shared_preferences.dart'; class LocalStorageService { Future<void> saveData(String key, String value) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(key, value); } Future<String?> getData(String key) async { final prefs = await SharedPreferences.getInstance(); return prefs.getString(key); } Future<void> deleteData(String key) async { final prefs = await SharedPreferences.getInstance(); await prefs.remove(key); } Future<void> clearAllData() async { final prefs = await SharedPreferences.getInstance(); await prefs.clear(); } }
3. UI or Controller Layer
Use this class in your widget or controller:
import 'package:flutter/material.dart'; import 'local_storage_service.dart'; class DeleteDataScreen extends StatelessWidget { final LocalStorageService _storageService = LocalStorageService(); void _deleteUserToken() async { await _storageService.deleteData('user_token'); } void _clearAll() async { await _storageService.clearAllData(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Delete Local Data')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: _deleteUserToken, child: Text('Delete User Token'), ), ElevatedButton( onPressed: _clearAll, child: Text('Clear All Data'), ), ], ), ), ); } }
Final Notes
Local data deletion should be handled with care to avoid unintentional data loss. Always confirm with the user when deleting critical information. For complex apps, consider alternatives like Hive
or ObjectBox
for structured local data handling.