Skip to content

Instantly share code, notes, and snippets.

@cachapa
Last active July 30, 2023 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cachapa/539dd1007fcf097179040f4056cdd4c7 to your computer and use it in GitHub Desktop.
Save cachapa/539dd1007fcf097179040f4056cdd4c7 to your computer and use it in GitHub Desktop.
A firedart TokenStore that uses Android and iOS preferences as persistence mechanism
import 'dart:convert';
import 'package:firedart/firedart.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// Stores tokens as preferences in Android and iOS.
/// Depends on the shared_preferences plugin: https://pub.dev/packages/shared_preferences
class PreferencesStore extends TokenStore {
static const keyToken = "auth_token";
static Future<PreferencesStore> create() async =>
PreferencesStore._internal(await SharedPreferences.getInstance());
SharedPreferences _prefs;
PreferencesStore._internal(this._prefs);
@override
Token read() => _prefs.containsKey(keyToken)
? Token.fromMap(json.decode(_prefs.get(keyToken)))
: null;
@override
void write(Token token) =>
_prefs.setString(keyToken, json.encode(token.toMap()));
@override
void delete() => _prefs.remove(keyToken);
}
@fleeser
Copy link

fleeser commented Aug 10, 2021

This won't work anymore due to null safety.

Use these two overrides instead:

@override Token? read() => _prefs.containsKey(keyToken) ? Token.fromMap(json.decode(_prefs.get(keyToken) as String)) : null;

@override void write(Token? token) => token != null ? _prefs.setString(keyToken, json.encode(token.toMap())) : null;

@peterBrxwn
Copy link

peterBrxwn commented Nov 4, 2021

When I call FirebaseAuth.initialize(apiKey, PreferencesStore());, I get this error message
The class 'PreferencesStore' doesn't have a default constructor.
@fleeser @cachapa

@hedihadi
Copy link

@peterBrxwn do it like this

  var firebaseAuth = FirebaseAuth.initialize(apiKey, await PreferencesStore.create());

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