我怎样才能使这项工作?我的共享偏好似乎存储了错误的值?
How can I make this work? My shared preferences seem to store the wrong value?
我有这些功能可以设置、删除等我希望全局可用的变量。我担心这可能只是我的一个小错误。我该怎么做才能解决这个问题?
static setUserId(userId, value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('userId', value);
}
static getUserId() async {
final prefs = await SharedPreferences.getInstance();
prefs.getInt('userId') ?? 0;
}
static removeUserId() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('userId');
}
static removeAllPreferences() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
}
var userId = user.id;
var value = userId?.toInt();
AccountPreferences.setUserId('userId', value);
var companyId = user.role![0].companyId;
var test = AccountPreferences.getUserId();
print(test); ```
When I run the code above all I print out is an instance of Future<dynamic>?
What am I doing wrong?
您还应该在获取值时等待,为此,您应该将函数 getUserId() 声明为 Future 并且 return 函数值如下所示:
static Future<int> getUserId() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt('userId') ?? 0;
}
var test = await AccountPreferences.getUserId(); // await inside here too, where you call it
我有这些功能可以设置、删除等我希望全局可用的变量。我担心这可能只是我的一个小错误。我该怎么做才能解决这个问题?
static setUserId(userId, value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('userId', value);
}
static getUserId() async {
final prefs = await SharedPreferences.getInstance();
prefs.getInt('userId') ?? 0;
}
static removeUserId() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('userId');
}
static removeAllPreferences() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
}
var userId = user.id;
var value = userId?.toInt();
AccountPreferences.setUserId('userId', value);
var companyId = user.role![0].companyId;
var test = AccountPreferences.getUserId();
print(test); ```
When I run the code above all I print out is an instance of Future<dynamic>?
What am I doing wrong?
您还应该在获取值时等待,为此,您应该将函数 getUserId() 声明为 Future 并且 return 函数值如下所示:
static Future<int> getUserId() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt('userId') ?? 0;
}
var test = await AccountPreferences.getUserId(); // await inside here too, where you call it