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

Viewed 165

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

3 Answers

just use the simple int _progs1; the error is coming because you are using the int with the future and you can not do the logical operators on futures because their value is unknown.

 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()

Thanks for the help Huthaifa. I tried out what you have suggest and it compiles without error. Unfortunately when i run the app i get a Exception Error by the press of the button.

enter image description here

I try to have 3 buttons on the Screen to change the value between 0 and 3. Button1 Up, Button2 Down, Button3 to put Zero. enter image description here

The following code is what i have with saving the value and without setting the Max and Min of the value.

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MyTest5Body extends StatefulWidget {
  @override
  _MyTest5BodyState createState() => _MyTest5BodyState();
}

class _MyTest5BodyState extends State<MyTest5Body> {
  final scaffoldKey = GlobalKey<ScaffoldState>();
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  Future<int> _progs1;

  Future<void> _incrementProgS1() async {
    final SharedPreferences prefs = await _prefs;
    final int progs1 = (prefs.getInt('progs1') ?? 0) + 1;

      setState(() {
        _progs1 = prefs.setInt("progs1", progs1).then((bool success) {
          return progs1;
        }) ;
      });
  }

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

  Future<void> _resetProgS1() async {
    final SharedPreferences prefs = await _prefs;
    final int progs1 = 0;
    setState(() {
      _progs1 = prefs.setInt("progs1", progs1).then((bool success) {
        return progs1;
      }) ;
    });
  }

  @override
  void initState() {
    super.initState();
    _progs1 = _prefs.then((SharedPreferences prefs) {
      return (prefs.getInt('progs1') ?? 0);
    }) ;
  }

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildListDelegate(
            [
              // Program Auswahl-------------------------------------------
              Container(
                height: 50.0,
                child: Row(children: <Widget>[
                  Container(
                    margin: const EdgeInsets.all(0),
                    child: TextButton(
                      onPressed: _incrementProgS1,
                      child: const Icon(Icons.arrow_upward, size: 30.0),
                      style: TextButton.styleFrom(
                        primary: Colors.orangeAccent[400],
                      ),
                    ),
                  ),
                  Container(
                      margin: const EdgeInsets.all(0),
                      child: TextButton(
                        onPressed: _decrementProgS1,
                        child: const Icon(Icons.arrow_downward, size: 30.0),
                        style: TextButton.styleFrom(
                            primary: Colors.greenAccent[700]),
                      )),
                  Container(
                      margin: const EdgeInsets.all(0),
                      child: TextButton(
                        onPressed: _resetProgS1,
                        child: const Icon(Icons.restore, size: 30.0),
                        style: TextButton.styleFrom(primary: Colors.blue[700]),
                      )),
                  Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 5.0, vertical: 5.0),
                      child: FutureBuilder<int>(
                          future: _progs1,
                          builder: (BuildContext context,
                              AsyncSnapshot<int> snapshot) {
                        switch (snapshot.connectionState) {
                          case ConnectionState.waiting:
                            return const CircularProgressIndicator();
                          default:
                            return Text(
                              '${snapshot.data} Program ',
                              style: TextStyle(
                                fontSize: 25.0,
                                fontWeight: FontWeight.bold,
                                letterSpacing: 2.0,
                                color: Colors.blueGrey[500],
                              ),
                            );
                        }
                      })),
                ]),
              ),
            ],
          ),
        ),
      ],
    );
  }
}


Related