Welcome to Persistent.
Add persistent
as a dev dependency in your pubspec.yaml file.
This contains the generator itself.
dev_dependencies:
persistent:
Add persistent_annotations
as a dependency in your pubspec.yaml file.
This contains the annotations that act as markers for the generator.
dependencies:
persistent_annotations:
Import the annotations and the local storage service to be used.
SharedPreferences for example.
import 'package:persistent_annotations:persistent_annotations.dart';
import 'package:shared_preferences:shared_preferences.dart';
Now, you're set to go.
Let's explain with an example.
A local user session is to be persisted. The data to persist locally, are an access token and its expiration date.
Let's get to it. We'll call the model LocalSessionApi
.
- First declare an abstract class for the generator.
Its name can be
LocalSessionApi
with the suffixBase
, which isLocalSessionApiBase
.
abstract class LocalSessionApiBase {
}
- Add the data to be persisted as late fields.
abstract class LocalSessionApiBase {
late String accessToken;
late DateTime expirationDate;
}
- Annotate the class and its fields.
@persistent
abstract class LocalSessionApiBase {
@Default('')
late String accessToken;
@Default('2022-9-10 15:04:07')
late DateTime expirationDate;
}
- Finally, generate.
flutter packages pub run build_runner build --delete-conflicting-outputs
You can also watch for any changes in code and rebuild accordingly. This can be faster during development of the classes.
flutter packages pub run build_runner watch --delete-conflicting-outputs
Everyone is more than welcomed to contribute to the code.
For any suggestions you can open an issue on github or DM me @ [email protected].