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

Issue

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?

Solution

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

Answered By – Wilson Toribio

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *