A code generator that provides strongly-typed accessors for Flutter shared_preferences entries.
- Check for duplicate keys
- Type-safe accessors for shared preferences
- Support for:
DateTime
enum
- Serializable objects with
fromJson
constructor andtoJson
method
Make sure to add these packages to the project dependencies:
flutter pub add --dev build_runner
flutter pub add --dev shared_preferences_gen
flutter pub add shared_preferences_annotation
If you are using json_serializable
, you need to add the following configuration to your build.yaml
file:
global_options:
json_serializable:
runs_before:
- shared_preferences_gen
This will ensure that the generated toJson
and fromJson
methods are available when analyzing the code.
Make sure to specify the correct file name in a part directive. In the example below, replace "name" with the file name.
import 'package:shared_preferences_annotation/shared_preferences_annotation.dart';
part 'name.g.dart';
To run the code generator, run the following commands:
dart run build_runner build --delete-conflicting-outputs
To create a shared preferences entry, first create an annotation @SharedPrefData
in the file where you want to store your instance of SharedPreferences
. Then add an entry with its corresponding type, key and default value (optional).
A SharedPrefEntry
can be used with any of those types:
bool
double
int
String
List<String>
DateTime
- Any
enum
- Any serializable object with a
toJson
method andfromJson
factory constructor
@SharedPrefData(entries: [
SharedPrefEntry<String>(key: 'myKey'),
])
void main() { /* ... */ }
You can access the generated entries directly from your instance of SharedPreferences
.
final prefs = await SharedPreferences.getInstance();
String myKey = prefs.myKey.value;
bool darkMode = prefs.darkMode.value;
final prefs = await SharedPreferences.getInstance();
await prefs.myKey.setValue('newValue');
final prefs = await SharedPreferences.getInstance();
await prefs.myKey.remove();
- Support for custom objects (no ETA)