How can I make this work? My shared preferences seem to store the wrong value?

omandersen

I have these functions to set, remove etc variables I want globally available. I fear it might be just a small mistake on my behalf. What can I do to fix this?

  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?
Wilson Toribio

You should also await when getting the value and for that, you should declare the function getUserId() as Future and also return the function value like this:

  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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324289859&siteId=291194637