Use the shared_preferences plugin in Flutter to save small bits of data. It's great for things like user settings or simple flags.
Why You Should Be Careful
Shared preferences are mainly for simple key-value pairs. They aren't built for complex data like lists of objects.
Limitations
They are not designed for fast reading and writing many items. Also, don't store sensitive information here. There's no guarantee that data written will always stay on the device, and sometimes data can be lost.
How to Get Started
You usually need to get an instance of SharedPreferences
. This is a future operation, so you'll need to await
it. It's a good practice to do this early in your app before showing your main screen.
import 'package:shared_preferences/shared_preferences.dart';
Future<void> loadPreferences() async {
final prefs = await SharedPreferences.getInstance();
// Now you can use 'prefs' to read and write data
}
Using with State Management
If you use libraries like Provider or Riverpod, you can set up shared preferences to be ready before your app shows anything. You can initialize it in a service class and make it available using the state management solution. The image shows an example using a SharedPreferencesBuilder
to make it accessible.
Looking Ahead
Keep in mind that the standard SharedPreferences
might be replaced or changed in the future. Newer options like SharedPreferencesAsync
or SharedPreferencesWithCache
are suggested alternatives.