JsonAdapter<T> class

A convenience adapter that handles common pitfalls when storing and retrieving JSON values.

JsonAdapter eliminates the need for a custom PreferenceAdapter. It also saves you from duplicating if (value == null) return null for custom adapters.

For example, if we have a class called SampleObject:

class SampleObject {
  SampleObject(this.isAwesome);
  final bool isAwesome;

  SampleObject.fromJson(Map<String, dynamic> json) :
    isAwesome = json['isAwesome'];

  Map<String, dynamic> toJson() => { 'isAwesome': isAwesome };
}

As seen from the above example, SampleObject implements both fromJson and toJson.

When present, JsonAdapter will call toJson automatically. For reviving, you need to provide a deserializer that calls fromJson manually:

final sampleObject = preferences.getCustomValue<SampleObject>(
  'my-key',
  adapter: JsonAdapter(
    deserializer: (value) => SampleObject.fromJson(value),
  ),
);

Using JsonAdapter with built_value

You can do custom serialization logic before JSON encoding the object by providing a serializer. Similarly, you can use deserializer to map the decoded JSON map into any object you want.

For example:

final sampleObject = preferences.getCustomValue<SampleObject>(
  'my-key',
  adapter: JsonAdapter(
    serializer: (value) => serializers.serialize(value),
    deserializer: (value) => serializers.deserialize(value),
  ),
);
Inheritance

Constructors

JsonAdapter({Object serializer(T)?, T deserializer(Object)?})
const

Properties

deserializer → (T Function(Object)?)
final
hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
serializer → (Object Function(T)?)
final

Methods

getValue(SharedPreferences preferences, String key) → T?
Retrieve a value associated with the key by using the preferences.
override
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
setValue(SharedPreferences preferences, String key, T value) Future<bool>
Set a value for the key by using the preferences.
override
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited