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

Time:03-24

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?

CodePudding user response:

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
  • Related