Cretezy / redux_persist

Persist Redux State
https://pub.dartlang.org/packages/redux_persist
MIT License
130 stars 41 forks source link

Using with built_value #22

Closed ianrothmann closed 6 years ago

ianrothmann commented 6 years ago

Hi there, Thanks for a great library!

Is there perhaps any guidance on using it with built_value to serialize/deserialize?

Kind regards,

Ian

Cretezy commented 6 years ago

Custom serializes are on the way in a future release! I'm sorry I haven't had much time to work on this recently

Cretezy commented 6 years ago

This was added in 0.8.0-rc.0, let me know if that fixes your problem!

Sorry for taking so long!

ianrothmann commented 6 years ago

Awesome, thank you so much!

On Tue, Nov 6, 2018 at 7:11 AM Charles Crete notifications@github.com wrote:

This was added in 0.8.0-rc.0, let me know if that fixes your problem!

Sorry for taking so long!

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/Cretezy/redux_persist/issues/22#issuecomment-436133066, or mute the thread https://github.com/notifications/unsubscribe-auth/AEHn94zdrgqge39RUvmx91K2Lih5WW5Wks5usRoBgaJpZM4WIPLB .

--

emaddoma commented 5 years ago

Any chance you could provide a quick example here as a reply of how to specify the serializer when using built_value?

Cretezy commented 5 years ago

I've never used built_value, so I unfortunately can't give an example. It shold be the same as any JSON though.

JinHoSo commented 5 years ago

@emaddoma You can use like this

import 'dart:convert';
import 'dart:typed_data';

import 'package:built_value/serializer.dart';
import 'package:flutter_redux_starter/data/util/serializers.dart';
import 'package:redux_persist/redux_persist.dart';

class BuiltValueSerializer<T> implements StateSerializer<T> {
  /// Turns the dynamic [json] (can be null) to [T]
  final Serializer<T> decoder;

  BuiltValueSerializer(this.decoder);

  @override
  T decode(dynamic data) {
    if(data == null){
      return null;
    }

    T deserializedData = serializers.deserializeWith(decoder, json.decode(uint8ListToString(data)));

    return deserializedData;
  }

  @override
  Uint8List encode(T state) {
    if (state == null) {
      return null;
    }

    Object serializedState = serializers.serializeWith(decoder, state);

    return stringToUint8List(json.encode(serializedState));
  }
}
  final persistor = Persistor<AppState>(
      storage: FlutterStorage(), // Or use other engines
      serializer: BuiltValueSerializer<AppState>(AppState.serializer));