Skip to content

Instantly share code, notes, and snippets.

@cachapa
Last active January 27, 2024 03:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cachapa/33944987bd8fe6c6ba84021cecef8fb7 to your computer and use it in GitHub Desktop.
Save cachapa/33944987bd8fe6c6ba84021cecef8fb7 to your computer and use it in GitHub Desktop.
import 'package:firedart/firedart.dart';
import 'package:hive/hive.dart';
/// Stores tokens using a Hive store.
/// Depends on the Hive plugin: https://pub.dev/packages/hive
class HiveStore extends TokenStore {
static const keyToken = "auth_token";
static Future<HiveStore> create() async {
// Make sure you call both:
// Hive.init(storePath);
// Hive.registerAdapter(TokenAdapter(), adapterId);
var box = await Hive.openBox("auth_store",
compactionStrategy: (entries, deletedEntries) => deletedEntries > 50);
return HiveStore._internal(box);
}
final Box _box;
HiveStore._internal(this._box);
@override
Token read() => _box.get(keyToken);
@override
void write(Token token) => _box.put(keyToken, token);
@override
void delete() => _box.delete(keyToken);
}
class TokenAdapter extends TypeAdapter<Token> {
@override
final typeId = 42;
@override
void write(BinaryWriter writer, Token token) =>
writer.writeMap(token.toMap());
@override
Token read(BinaryReader reader) =>
Token.fromMap(reader.readMap().map<String, dynamic>(
(key, value) => MapEntry<String, dynamic>(key, value)));
}
@guyluz11
Copy link

guyluz11 commented Jun 2, 2021

With

environment:
  sdk: '>=2.12.0 <3.0.0'

This code will not work as it does not support the null safe (and it extends TokenStore).
You will get some errors.

In order to fix this you need to add ? to both @override Token read() and @override void write(Token token) override methods like this:

  @override
  Token? read() => _box.get(keyToken);

  @override
  void write(Token? token) => _box.put(keyToken, token);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment