🚰 A BehaviorSubject for Flutter with automatic persist and hydrate

Related tags

Templates hydrated
Overview

Hydrated

Version Build License

Hydrated provides a Subject that automatically persists to Flutter's local storage and hydrates on creation!

Easy to consume

All values are persisted with shared_preferences and restored with automatic hydration.

final count$ = HydratedSubject<int>("count", seedValue: 0);

/// count$ will automagically be hydrated with 42 next time it is created
count$.add(42);

Ready for BLoC

class HydratedBloc {
  final _count$ = HydratedSubject<int>("count", seedValue: 0);

  ValueObservable<int> get count$ => _count$.stream;
  Sink<int> get setCount => _count$.sink;

  dispose() {
    _count$.close();
  }
}

Supports simple types and serialized classes

We support all shared_preferences types.

  • int
  • double
  • bool
  • String
  • List<String>
final count$ = HydratedSubject<int>("count");

We also support serialized classes with hydrate and persist arguments.

final user$ = HydratedSubject<User>(
  "user",
  hydrate: (String s) => User.fromJson(s),
  persist: (User user) => user.toJson(),
);

Reliable

Hydrated is mock tested with all supported types and is dogfooded by its creator.

Extensible

Hydrated supports any key-value data storages -- just implement the KeyValueStore interface and you will be able to use hive, flutter_secure_storage or any other persistence solution of your choice.

class MyAwesomeKeyValueStore implements KeyValueStore {
  /// your implementation here...
}

final user = HydratedSubject<User>(
  "user",
  hydrate: (String s) => User.fromJson(s),
  persist: (User user) => user.toJson(),
  keyValueStore: MyAwesomeKeyValueStore()
);

Demo

demo of Hydrated BehaviorSubject between app restarts

Original developer

hydrated was originally developed by @lukepighetti.

Comments
  • Abstract methods to store/load the object

    Abstract methods to store/load the object

    I love this feature to persist the value on the Bloc. However shared preferences dependency makes it Flutter only package (maybe it is fine for now). In case of Bloc pattern, it should not know anything about Flutter, because we could use that Bloc on AngularDart for example. Probably Hummingbird will make AngularDart obsolete but not sure when that can happen.

    I think this package can go to Dart-only and provide flutter (shared preference, etc.) overrides, also will give any other future storage mechanisms (Firebase for example).

    Suggestion: AbstractHydrate with methods to override: Fetches from a storage by a key (current HydrateSubject could override this with SharedPreferences use)

    T fetch() {
    }
    

    Stores value (serializes if needed/supported) and current HydrateSubject can override this with current implementation.

    store(T val) {
    }
    

    This would allow to have the hydrate package Dart only, and 'flutter_hydrate' (or other name) for example use SharedPreferences. In future more "plugin" packages can be created to serialize or store to DB or store to file, even Firebase.

    Just idea, see my https://pub.dartlang.org/packages/flutter_fimber and https://pub.dartlang.org/packages/fimber packages that follows that logic.

    opened by magillus 11
  • First try at allowing alternative hydrate and persist implementations

    First try at allowing alternative hydrate and persist implementations

    Now common code is in AbstractHydratedSubject.

    When creating a custom HydratedSubject, you just need to override hydrate/_persistValue and implement the constructors. HydratedSetup also helps will some common code needed in the constructors.

    opened by MisterJimson 5
  • Update to rxdart 0.21

    Update to rxdart 0.21

    I tried to use the package but requires rxdart 0.20. I don't think I have something that can benefit from 0.21 but would be ok to update the package to 0.21. Thanks

    opened by cosinus84 4
  • Question: How could I persist a list of a model

    Question: How could I persist a list of a model

    Hello, I'm a flutter newbee.

    I'm storing a token using this and it's working like a charm. Now I would like to know how to store a list of houses.

    I have a list of favorite houses in my bloc. Like this:

    ...
    BehaviorSubject<List<House>> _favoritesController = BehaviorSubject<List<House>>(seedValue: <House>[]);
    Stream<List<House>> get favorites => _favoritesController.stream;
    ...
    

    Is it possible to persist this list?

    Thank you.

    opened by devfelipereis 3
  • ver. shared_preferences

    ver. shared_preferences

    I do not know if it's an issue, but when I installed it, there was a compatibility error, because there is a new version shared_preferences, which was in my project previously

    opened by marrullas 3
  • Add support for a generic persistence interface

    Add support for a generic persistence interface

    Resolves #23

    While working on the PR, I realized that the generic persistence can be done for basically any persistent data storage, not only the key-value one.

    opened by solid-yuriiprykhodko 2
  • Add support for generic persistence interface -- alternative 1

    Add support for generic persistence interface -- alternative 1

    Resolves #23 Alternative to #26

    Abstracts away only the key-value store. The persistence key and also the hydrate and persist callbacks are kept in the HydratedSubject class, avoiding breaking changes.

    opened by solid-yuriiprykhodko 1
  • Can I use this for user profile storing whenever user login.

    Can I use this for user profile storing whenever user login.

    Right now I am using streambuilder to fetch user data to show it in drawer menu. Every time user see drawer screen future are taking time to interact with network call and render the data. Can I use hydrated package to store user data whenever he logins ?

    thank you.

    opened by Flutter-Stack 1
  • Update if _hydrateSubject order

    Update if _hydrateSubject order

    To avoid ambiguity it is best to keep the persistence test first. This has already caused a problem in a project of mine where I use it within a class with

    opened by jacobaraujo7 1
  • Consider supporting a generic persistence interface

    Consider supporting a generic persistence interface

    Use cases:

    1. Custom wrappers over SharedPreferences -- some projects abstract away from persistence, making this package a bad choice for them, since we only support stock SharedPreferences.
    2. Secure storage -- while iOS should be good to go, sharedpreferences on Android is not the most secure way to store data. Adding a generic interface should give the user freedom of choice when it comes to choosing the layer which does the actual key/value persistence.

    In general the idea is to abstract away from details on how we do persistence, and turn this package into a generic reactive extension for a keyed storage.

    enhancement 
    opened by solid-yuriiprykhodko 0
  • The source must not be null

    The source must not be null

    [VERBOSE-2:shell.cc(186)] Dart Error: Unhandled exception:
    Invalid argument(s): The source must not be null
    #0      int.parse (dart:core/runtime/libintegers_patch.dart:51:25)
    #1      new AdvertisingService.<anonymous closure> (package:when_coin/services/advertising.dart:41:62)
    #2      HydratedSubject._hydrateSubject (package:hydrated/hydrated.dart:140:18)
    <asynchronous suspension>
    #3      new HydratedSubject._ (package:hydrated/hydrated.dart:58:5)
    #4      new HydratedSubject (package:hydrated/hydrated.dart:89:16)
    #5      new AdvertisingService (package:when_coin/services/advertising.dart:39:30)
    #6      main (package:when_coin/main.dart:5:16)
    #7      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:289:19)
    #8      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
    
    opened by lukepighetti 0
  • Support custom `persist` and `hydrate` callbacks for primitive types.

    Support custom `persist` and `hydrate` callbacks for primitive types.

    As pointed out by @solid-vovabeloded: Currently if we use HydratedSubject with a primitive type, custom persist and hydrate callbacks won't be invoked, or used at all: image

    The idea is to change the check order in the above method to use the custom callbacks, if they were provided, and then fall back to standard handling.

    enhancement 
    opened by solid-yuriiprykhodko 0
Releases(2.1.0)
Automatic source code generation for Dart

Overview source_gen provides utilities for automated source code generation for Dart: A framework for writing Builders that consume and produce Dart c

Dart 418 Dec 30, 2022
Flutter widget to change `themeMode` during runtime and persist it across restarts.

theme_mode_handler Flutter widget to change themeMode during runtime and persist it across restarts. Motivation Flutter 1.9 introduced a new way to co

Arthur Denner 28 Oct 29, 2022
Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's information in Flutter.

Flutter Tutorial - User Profile & SharedPreferences Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's inf

Johannes Milke 21 Dec 3, 2022
Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web.

Flutter Tutorial - Hive NoSQL Database Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web. ✌  Preview App Preview Course Pr

Johannes Milke 54 Dec 31, 2022
Small Flutter app that uses SQLite to persist data.

Crud_With_Flutter_And_Sqlite A new Flutter project. The application allows you to register a user with your name and email, edit and also delete. All

Idelfonso Joás 0 Oct 22, 2022
State Persistence - Persist state across app launches. By default this library store state as a local JSON file called `data.json` in the applications data directory. Maintainer: @slightfoot

State Persistence Persist state across app launches. By default this library store state as a local JSON file called data.json in the applications dat

Flutter Community 70 Sep 28, 2022
A beautiful, secure and simple authenticator app that supports multiple protocols and services. Free and open source. Written in Flutter and Dart.

OpenAuth A beautiful, secure and simple authenticator app that supports multiple protocols and services. Free and open source. Written in Flutter and

Isaiah Collins Abetong 31 Oct 5, 2022
Codeflow 19 Sep 29, 2022
Find The Latest trending and upcoming movies and tv shows with MovieDB app. The app contains all info about movies and tv shows. find similar movies or shows, Browse all genres, video trailers, backdrops, logos, and posters.

MovieDB App Features. Dynamic Theming Search Functionality Onboarding-Screen Select favourite movie Home Screen Tranding movie Movies different catego

Ansh rathod 80 Dec 12, 2022
WooCommerce App template that uses Flutter. Integrated to work with WooCommerce stores, connect and create an IOS and Android app from Flutter for IOS and Android

WooCommerce App: Label StoreMax Label StoreMax - v5.3.1 Official WooSignal WooCommerce App About Label StoreMax Label StoreMax is an App Template for

WooSignal 314 Jan 9, 2023
A Flutter application with proper navigation and routes handling and API data fetching and posting.

Flutter-Navigation-and-API-Integration A Flutter application with proper navigation and routes handling and API data fetching and posting. ⏮ Preview G

Ehmad Saeed⚡ 7 Oct 5, 2022
A wrapper around our Cocoa and Java client library SDKs, providing iOS and Android support for those using Flutter and Dart.

Ably Flutter Plugin A Flutter plugin wrapping the ably-cocoa (iOS) and ably-java (Android) client library SDKs for Ably, the platform that powers sync

Ably Realtime - our client library SDKs and libraries 46 Dec 13, 2022
Dart and Flutter sealed class generator and annotations, with match methods and other utilities. There is also super_enum compatible API.

Dart Sealed Class Generator Generate sealed class hierarchy for Dart and Flutter. Features Generate sealed class with abstract super type and data sub

6thSolution 15 Jan 2, 2023
flutter_thrio makes it easy and fast to add flutter to existing mobile applications, and provide a simple and consistent navigator APIs.

中文文档 英文文档 问题集 原仓库不再维护,代码已经很老了 最近版本更新会很快,主要是增加新特性,涉及到混合栈的稳定性的问题应该不多,可放心升级,发现问题加 QQ 群号码:1014085473,我会尽快解决。 不打算好好看看源码的使用者可以放弃这个库了,因为很多设定是比较死的,而我本人不打算花时间写

null 290 Dec 29, 2022
Flutterbodydetection - A flutter plugin that uses MLKit on iOS/Android platforms to enable body pose and mask detection using Pose Detection and Selfie Segmentation APIs for both static images and live camera stream.

body_detection A flutter plugin that uses MLKit on iOS/Android platforms to enable body pose and mask detection using Pose Detection and Selfie Segmen

null 18 Dec 5, 2022
flutter_thrio makes it easy and fast to add flutter to existing mobile applications, and provide a simple and consistent navigator APIs.

本仓库不再维护,可移步新仓库 https://github.com/flutter-thrio/flutter_thrio 中文文档 问题集 QQ 群号码:1014085473 The Navigator for iOS, Android, Flutter. Version 0.2.2 requir

Hellobike 732 Dec 5, 2022
A blogging application where users can publish their blogs and articles and can connect with other authors, developed using Flutter and Firebase.

Utopia About the app A blogging application where users can publish their blogs and articles and can connect with other authors, developed using Flutt

Utopia 12 Jan 3, 2023