I am trying to implement the package shared_preferences in my Flutter app.
I have included the package inside the pubspec.yaml file.
I have created a helper class called StorageUtil to manage shared_preferences in the project.
This is shared_preferences_util.dart:
import 'package:shared_preferences/shared_preferences.dart';
class StorageUtil {
static StorageUtil _storageUtil;
static SharedPreferences _preferences;
static Future<StorageUtil> getInstance() async {
if (_storageUtil == null) {
// keep local instance till it is fully initialized.
var secureStorage = StorageUtil._();
await secureStorage._init();
_storageUtil = secureStorage;
}
return _storageUtil;
}
StorageUtil._();
Future _init() async {
_preferences = await SharedPreferences.getInstance();
}
// get string
static String getString(String key, {String defValue = ''}) {
if (_preferences == null) return defValue;
return _preferences.getString(key) ?? defValue;
}
// put string
static Future<bool> putString(String key, String value) {
if (_preferences == null) return null;
return _preferences.setString(key, value);
}
}
Then at file notification_service.dart I am creating an item inside shared_preferences:
_refreshToken() {
_firebaseMessaging.getToken().then((token) async {
print('token: $token');
StorageUtil.putString("token_firebase", token.toString());
print('token despues de shared:' + token);
}, onError: _tokenRefreshFailure);
}
Print output:
I/flutter (29912): token despues ed shared:fy0Pk1asTOejYrWYXbULBu:APA91bGk2TLqdiLbGvZp7IrTggLfjwYcvhENB83RQj-7x1CEPoou_cY7Rq0eB6rFqEfb386pxSsWAogRc8HwQjK0Y9q9kyKgzSJ6ZCQ3qhFBIjaLhS2sZKJ-N1k7hdrRHdboyUb3WvGS
And later I am trying to get the shared_preferences item as follows:
final _tokenFb = StorageUtil.getString("token_firebase");
But it is always and empty String.
print("Token firebase en authbloc: " + _tokenFb);
Output:
I/flutter (29912): Token firebase en authbloc:
What am I missing?
_preferences
is null since you aren't calling await StorageUtil.getInstance()
on your class. Therefore the _init
method isn't called and SharedPreferences
isn't being initialized.
You should call it like this:
_refreshToken() {
_firebaseMessaging.getToken().then((token) async {
print('token: $token');
var storageUtil = await StorageUtil.getInstance();
storageUtil.putString("token_firebase", token.toString());
print('token despues de shared:' + token);
}, onError: _tokenRefreshFailure);
}
And the same goes for StorageUtil.getString
of course.