widget_hydrator 0.0.1 copy "widget_hydrator: ^0.0.1" to clipboard
widget_hydrator: ^0.0.1 copied to clipboard

A powerful Flutter mixin for effortless StatefulWidget state persistence and hydration. Provides automatic saving and restoring of widget state across app restarts, with support for encryption, compre [...]

Widget Hydrator #

Table of Contents #

  1. Introduction
  2. Installation
  3. Basic Usage
  4. Advanced Features
  5. API Reference
  6. Configuration
  7. Best Practices
  8. Troubleshooting

Introduction #

Widget Hydrator is a powerful Flutter package that provides an easy and flexible way to persist and restore the state of your StatefulWidgets between app restarts. By using a single mixin, you can add robust state persistence to your widgets with minimal effort.

Key features include:

  • Automatic state persistence and hydration
  • Compression and encryption support
  • In-memory caching for improved performance
  • Undo/Redo functionality
  • State migration support
  • Selective persistence
  • State snapshots
  • Performance metrics

Installation #

To use Widget Hydrator in your Flutter project, add it to your pubspec.yaml:

dependencies:
  widget_hydrator: ^1.0.0

Then run:

flutter pub get

Basic Usage #

  1. Import the package in your Dart file:
import 'package:widget_hydrator/widget_hydrator.dart';
  1. Add the UltimateHydrationMixin to your StatefulWidget's State class:
class _MyWidgetState extends State<MyWidget> with UltimateHydrationMixin {
  String _myStateVariable = '';

  @override
  Map<String, dynamic> persistToJson() {
    return {
      'myStateVariable': _myStateVariable,
    };
  }

  @override
  void hydrateFromJson(Map<String, dynamic> json) {
    _myStateVariable = json['myStateVariable'] as String;
  }

  @override
  void initializeDefaultState() {
    _myStateVariable = 'Default Value';
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: ensureHydrated(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return Text(_myStateVariable);
        } else {
          return CircularProgressIndicator();
        }
      },
    );
  }
}

Advanced Features #

Selective Persistence #

Persist only specific parts of your state:

persistSelectedKeys(['key1', 'key2']);

State Snapshots #

Create and restore named snapshots of your state:

createSnapshot('beforeImportantChange');
// ... make changes ...
restoreSnapshot('beforeImportantChange');

Undo/Redo #

Implement undo and redo functionality:

undo();
redo();

State Observers #

Add observers to be notified of state changes:

addStateObserver((state) {
  print('State changed: $state');
});

Performance Metrics #

Track hydration and persistence performance:

final metrics = getPerformanceMetrics();
print('Hydration took ${metrics['hydrationDuration']}ms');

Custom Serialization #

Handle complex objects with custom serialization:

setCustomSerializer(
  (obj) => (obj as ComplexObject).toJson(),
  (json) => ComplexObject.fromJson(json as Map<String, dynamic>)
);

API Reference #

UltimateHydrationMixin #

Methods to Implement

  • Map<String, dynamic> persistToJson()
  • void hydrateFromJson(Map<String, dynamic> json)
  • void initializeDefaultState()

Optional Methods

  • Future<Map<String, dynamic>> migrateState(Map<String, dynamic> oldState)

Public Methods

  • Future<void> ensureHydrated()
  • Future<void> forcePersist()
  • Future<void> forceHydrate()
  • Future<void> clearPersistedState()
  • Future<void> saveState({VoidCallback? onSaveComplete})
  • void setAutoSaveInterval(Duration interval)
  • void disableAutoSave()
  • Future<void> persistSelectedKeys(List<String> keys)
  • Future<void> createSnapshot(String snapshotName)
  • Future<void> restoreSnapshot(String snapshotName)
  • void undo()
  • void redo()
  • void addStateObserver(Function(Map<String, dynamic>) observer)
  • void removeStateObserver(Function(Map<String, dynamic>) observer)
  • Map<String, int> getPerformanceMetrics()
  • void setCustomSerializer(Function(dynamic) serializer, Function(dynamic) deserializer)

Configuration Methods

  • void enableCompression(bool enable)
  • void enableEncryption(bool enable)
  • void setEncryptionKey(String key)
  • void setVersion(int version)
  • void setStateExpirationDuration(Duration? duration)

Configuration #

Compression #

Enable compression to reduce storage space:

enableCompression(true);

Encryption #

Enable encryption for sensitive data:

enableEncryption(true);
setEncryptionKey('your-secret-key');

State Expiration #

Set an expiration time for persisted state:

setStateExpirationDuration(Duration(days: 7));

Best Practices #

  1. Implement persistToJson() and hydrateFromJson() methods to handle all state variables you want to persist.
  2. Use ensureHydrated() in your build method to ensure the state is loaded before rendering.
  3. Implement initializeDefaultState() to set default values when no persisted state is available.
  4. Use migrateState() to handle version changes in your persisted state structure.
  5. Consider using compression for large states and encryption for sensitive data.
  6. Use selective persistence for large states where only part of the state needs to be persisted.
  7. Implement custom serializers for complex objects that aren't natively serializable.

Troubleshooting #

State Not Persisting #

  • Ensure persistToJson() includes all necessary state variables.
  • Check if ensureHydrated() is called before accessing the state.
  • Verify that initializeDefaultState() is implemented correctly.

Performance Issues #

  • Use the getPerformanceMetrics() method to identify bottlenecks.
  • Consider enabling compression for large states.
  • Use in-memory caching by default to reduce disk I/O.

Encryption Errors #

  • Ensure the encryption key is set correctly with setEncryptionKey().
  • Verify that encryption is enabled with enableEncryption(true).

For more assistance, please file an issue on the GitHub repository.

5
likes
0
points
80
downloads

Publisher

unverified uploader

Weekly Downloads

A powerful Flutter mixin for effortless StatefulWidget state persistence and hydration. Provides automatic saving and restoring of widget state across app restarts, with support for encryption, compression, versioning, and cross-platform storage. Features include selective persistence, state snapshots, undo/redo functionality, and performance metrics.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

archive, crypto, encrypt, flutter, hive, mockito, path_provider, universal_io

More

Packages that depend on widget_hydrator