Flutter: Using Shared Preferences and set min and max value for a variable
Solution 1
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()
Solution 2
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.
Carlos Costa
Updated on December 31, 2022Comments
-
Carlos Costa over 1 year
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
-
Carlos Costa almost 3 yearsThanks Asim for the quick response. I tried already using only "int _progs1;". After i get the error, "A value of type 'Future<int>' can't be assigned to a variable of type 'int'. Try changing the type of the variable, or casting the right-hand type to 'int'.". If i change the type to "var" or i make "casting the right-hand type to 'int'", i get no error, but like this i'm loosing the Functionality to maintain the value always i restart the app
-
Huthaifa Muayyad over 2 yearsIf this has helped you in your original post, kindly mark it as an answer to your question, thanks.