Last active
July 30, 2023 11:56
-
-
Save cachapa/539dd1007fcf097179040f4056cdd4c7 to your computer and use it in GitHub Desktop.
A firedart TokenStore that uses Android and iOS preferences as persistence mechanism
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
@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
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;