What is Shared Preferences in Flutter?

Shared Preferences is a key-value storage mechanism that enables Flutter developers to store and retrieve data persistently on a device. It’s ideal for saving user preferences, configuration settings, or any lightweight data that needs to persist between app sessions.

Shared Preferences in Flutter

Benefits of Using Shared Preferences

Key Features of Shared Preferences

  1. Key-Value Pair Storage: Data is stored as a pair where each key corresponds to a specific value.
  2. Primitive Data Types: Supports basic types like int, double, bool, String, and List<String>.
  3. Asynchronous Access: Uses asynchronous APIs to prevent UI blocking during read/write operations.

How to Use Shared Preferences in Flutter

1. Add the Dependency

To use Shared Preferences, include the plugin in your pubspec.yaml file:

dependencies:  
shared_preferences: ^2.1.0

Run flutter pub get to install the package.

2. Import the Package

In your Dart file, import the shared_preferences library:

import 'package:shared_preferences/shared_preferences.dart';  

3. Save Data

To save data, use the set methods available for each data type:

Future<void> saveData() async {  
final prefs = await SharedPreferences.getInstance();
await prefs.setString('username', 'JohnDoe');
await prefs.setInt('age', 25);
await prefs.setBool('isLoggedIn', true);
}

4. Retrieve Data

To retrieve data, use the get methods:

Future<void> retrieveData() async {  
final prefs = await SharedPreferences.getInstance();
String? username = prefs.getString('username');
int? age = prefs.getInt('age');
bool? isLoggedIn = prefs.getBool('isLoggedIn');

print('Username: $username, Age: $age, Logged In: $isLoggedIn');
}

5. Remove Data

To delete specific data, use the remove method:

Future<void> removeData() async {  
final prefs = await SharedPreferences.getInstance();
await prefs.remove('username');
}

6. Clear All Data

To clear all stored data, use the clear method:

Future<void> clearAllData() async {  
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}

Best Practices for Using Shared Preferences

Common Use Cases for Shared Preferences

  1. User Authentication State: Save whether a user is logged in.
  2. App Themes: Store the user’s theme preference (dark/light mode).
  3. Language Settings: Persist the selected language across app launches.
  4. Introductory Screens: Track whether the user has seen the onboarding screens.

Limitations of Shared Preferences

Conclusion

Shared Preferences is a powerful tool in Flutter for handling lightweight persistent storage. With its simple API and cross-platform compatibility, it’s an excellent choice for saving app settings and user preferences. By following the best practices outlined in this guide, you can effectively leverage Shared Preferences to enhance your app’s user experience.

FAQs

Q1: Can I store complex objects in Shared Preferences?
No, Shared Preferences supports only primitive data types. However, you can serialize complex objects to JSON strings and store them as String.

Q2: Is Shared Preferences secure?
No, data stored in Shared Preferences is not encrypted. Use secure storage plugins like flutter_secure_storage for sensitive data.

Q3: What is the size limit for Shared Preferences?
There’s no explicit size limit, but it’s designed for small amounts of data. Storing large data can impact performance.

Explore Other Flutter Topics…

  1. Introduction to Flutter and Dart
  2. Why choose Flutter
  3. Installing Flutter On Your Windows Mac And Linux System
  4. Your first Flutter app
  5. Flutter project structure
  6. Building blocks of Flutter
  7. Stateful vs. Stateless Widgets Explained
  8. Flutter layout system
  9. Flutter text widget
  10. Creating Buttons in Flutter: ElevatedButton, TextButton, and IconButton
  11. Handling User Input with Flutter Forms
  12. Container class in Flutter
  13. Flutter Navigation
  14. Flutter – Pass Data One Screen To Another Screen
  15. Managing Device Orientation in Flutter
  16. Stateful widget lifecycle in Flutter
  17. Future of Flutter
  18. Flutter Themes
  19. Flutter Animations
  20. Flutter AppBar Customization
  21. ListView in Flutter
  22. Flutter GridView
  23. Flutter Expanded Widget
  24. Flutter BottomNavigation Bar
  25. Floating Action Button
  26. Drawer Widgets in Flutter
  27. Form Validation in Flutter
  28. Flutter TextField
  29. Adding AdMob ads to a Flutter app
  30. Building Flutter Web & Desktop Applications
  31. What is Async and Await in Flutter
  32. HTTP requests in Flutter
  33. Parsing JSON in Flutter
  34. Tinder-Style Swipe Cards in Flutter
  35. Flutter Tic Tac Toe Game Tutorial
  36. Flutter Login UI Tutorial
  37. Flutter Card Widget Tutorial
  38. Flutter music player app tutorial
  39. Flutter introduction screens
  40. Shared Preferences in Flutter
  41. SQLite Database in Flutter
  42. Firebase Authentication in Flutter
  43. Firebase Firestore in Flutter
  44. Push Notifications in Flutter
  45. Handling File Uploads in Flutter
  46. Responsive Design in Flutter
  47. Provider in Flutter
  48. Riverpod in Flutter
  49. Flutter BLoC Pattern Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *