Shared Preferences in Flutter
30 March, 2023
1
1
0
Contributors
Shared Preferences is a simple, lightweight solution for storing small amounts of data in key-value pairs. It is part of the flutter:services
library and allows you to save persistent data that needs to be retained across app launches.
Shared Preferences is useful for storing simple data such as user preferences, settings, and small bits of information that need to be persisted between app launches. The data is stored as key-value pairs, with the keys being strings and the values being one of the following types:
bool
double
int
String
Here is an example of how to use Shared Preferences in Flutter:
import 'package:flutter/services.dart';
// Get a reference to the Shared Preferences
final prefs = await SharedPreferences.getInstance();
// Save a value to the Shared Preferences
prefs.setString('username', 'johnsmith');
// Retrieve a value from the Shared Preferences
String username = prefs.getString('username');
print(username); // Output: "johnsmith"
For more information, you can refer to the official documentation: https://api.flutter.dev/flutter/services/SharedPreferences-class.html
Handy Packages
In Flutter, the shared_preferences
package is the most commonly used package for working with shared preferences. It provides a simple API for storing and retrieving data in key-value pairs, and it is built on top of the flutter:services
library.
You can find more information about the shared_preferences
package in the official documentation: https://pub.dev/packages/shared_preferences
There are also other packages available for working with shared preferences in Flutter. Here are a few alternatives:
flutter_secure_storage
: This package provides a secure storage solution for storing sensitive data such as passwords and authentication tokens. Documentation: https://pub.dev/packages/flutter_secure_storageflutter_local_notifications
: This package allows you to display notifications in the device's notification drawer. It also provides a way to store notification-related data using shared preferences. Documentation: https://pub.dev/packages/flutter_local_notificationsflutter_key_value_store
: This is a lightweight package for working with shared preferences that provides a simple API for storing and retrieving data. Documentation: https://pub.dev/packages/flutter_key_value_store