As we build increasingly complex Flutter applications, there will come a time when you need to store data locally on the user's device. This is crucial for providing a seamless user experience, allowing data to persist even when the app is closed and reopened. Flutter offers excellent solutions for this, broadly categorized into simple preferences and more robust local databases.
When you need to store small amounts of simple data like user settings, themes, or flags, shared_preferences is your go-to package. It provides a straightforward way to save and retrieve primitive data types (strings, integers, booleans, doubles, and lists of strings) using a key-value pair system.
First, add the shared_preferences package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.15Then, import the package into your Dart file:
import 'package:shared_preferences/shared_preferences';Here's how you can save a boolean value (e.g., for dark mode preference):
Future<void> saveDarkModePreference(bool isDarkMode) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('darkMode', isDarkMode);
}And here's how to retrieve that value:
Future<bool> getDarkModePreference() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool('darkMode') ?? false; // Default to false if not set
}