Skip to content

Conversation

@meylis1998
Copy link

Summary

Adds optional cache expiration support to HydratedBloc and HydratedCubit to automatically clear cached state after a specified duration.

Changes

  • Added optional expirationDuration parameter to HydratedBloc and HydratedCubit constructors
  • Cached state with expiration wraps data with timestamp metadata
  • Expired state returns default state and is automatically cleared from storage
  • Fully backward compatible - existing blocs work without changes
  • Handles legacy data gracefully (data without timestamp wrapper)

Storage Format

When expiration is enabled:

{
  "__hydrated_state__": { "value": 42 },
  "__hydrated_timestamp__": 1234567890
}

When expiration is disabled (default/legacy):

{ "value": 42 }

Example Usage

class CounterCubit extends HydratedCubit<int> {
  CounterCubit()
      : super(
          0,
          expirationDuration: const Duration(days: 7),
        );

  void increment() => emit(state + 1);

  @override
  int fromJson(Map<String, dynamic> json) => json['value'] as int;

  @override
  Map<String, int> toJson(int state) => {'value': state};
}

Test Coverage

  • 12 new tests covering expiration logic, edge cases, and backward compatibility
  • All 132 tests passing
  • 100% test coverage for new code

Checklist

  • Code formatted with dart format .
  • Code analyzed with dart analyze --fatal-infos --fatal-warnings .
  • All tests passing
  • Documentation updated (README.md)
  • Backward compatible

Fixes #4381

Adds optional expirationDuration parameter to HydratedBloc and HydratedCubit that allows cached state to expire after a specified duration.

Features:
- Optional expirationDuration parameter in constructors
- Expired state automatically cleared from storage
- Fully backward compatible (defaults to no expiration)
- Handles legacy data without timestamp wrapper

Fixes felangel#4381
@meylis1998 meylis1998 requested a review from felangel as a code owner October 5, 2025 10:23
@felangel felangel added enhancement New feature or request pkg:hydrated_bloc This issue is related to the hydrated_bloc package labels Nov 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request pkg:hydrated_bloc This issue is related to the hydrated_bloc package

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(hydrated_bloc): add support for an expiration time on cached values

2 participants