Search code examples
flutterdartsharedpreferences

Flutter: Using Shared Preferences and set min and max value for a variable


I am using a variable called "int _progs1 = 0;". This variable i can set with a "if statement" to a max and min value, that it does not go over or under the specified value.

int _progs1 = 0;

TextButton(
       onPressed: () {
        if (_progs1 < 3)
         setState(() {
           _progs1 += 1;
             });
              debugPrint(' $_progs1 Up');
             },

TextButton(
       onPressed: () {
        if (_progs1 > 0)
         setState(() {
           _progs1 -= 1;
             });
              debugPrint(' $_progs1 Down');
             },

Trying to use the same method with Shared Preferences that it can store the value it gives me the error.

"The operator '<' isn't defined for the type 'Future'. Try defining the operator '<'."

  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  Future<int> _progs1;

  Future<void> _decrementProgS1() async {
    final SharedPreferences prefs = await _prefs;
    final int progs1 = (prefs.getInt('progs1') ?? 0) - 1;
    if (_progs1 < 3)
    setState(() {
      _progs1 = prefs.setInt("progs1", progs1).then((bool success) {
        return progs1;
      });
    });
  }

What I am doing wrong? Is my approach wrong? Is there a better way to make it? To be able to go up and down with a variable between defined values and store it at the same time.

Thanks in advance


Solution

  •  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
     int _progs1;
    
      Future<void> _decrementProgS1() async {
        final SharedPreferences prefs = await _prefs;
        final int progs1 = await ((prefs.getInt('progs1') ?? 0) - 1);
        if (_progs1 < 3)
        {
          _progs1 = prefs.setInt("progs1", progs1).then((bool success) {
            return progs1;
          });
        }
      }
    

    You don't need setState either. When you want to use the function _decrementProgS1() use await with it, like this:

    _progs1 = await _decrementProgS1()