I am currently working on an editable profile. But as I run the project I receive the following error:
The method 'getString' was called on null. Receiver: null
Tried calling: getString("aresraa")
How to proceed forward?
class UserPreferences {
static SharedPreferences _preferences;
static const _keyUser = 'aresraa';
static const myUser = User(
imagePath:
'https://images.unsplash.com/photo-1554151228-14d9def656e4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=333&q=80',
name: 'Aresrana',
isDarkMode: false,
);
static Future init() async =>
_preferences = await SharedPreferences.getInstance();
static Future setUser(User user) async {
final json = jsonEncode(user.toJson());
await _preferences.setString(_keyUser, json);
}
static User getUser() {
final json = _preferences.getString(_keyUser);
return json == null ? myUser : User.fromJson(jsonDecode(json));
}
}
CodePudding user response:
You can check if _preferences
is null and get the instance again. Shared Preferences gives you the singleton instance.
static User getUser() {
_preferences ??= await SharedPreferences.getInstance();
final json = _preferences.getString(_keyUser);
return json == null ? myUser : User.fromJson(jsonDecode(json));
}
CodePudding user response:
The best way for you to find out is to do this exercises, 60 min and you will understand whole problem. -> https://dart.dev/codelabs/null-safety