i get int? variable from SharedPreferences class with getInt() method. I have to put this int? as a parameter for Duration Object but i need to have an int. What can I do? This is the code:
int? duration = ParametersHelper.getDuration();
Future.delayed(const Duration(milliseconds: duration));
This is getDuration() method in ParametersHelper:
static int? getDuration() {
return _pref.getInt("Duration");
}
Thank you!
CodePudding user response:
You can either override this behavior by explicitly telling the dart compiler that although the variable can be nullable I guarantee that it's not null, be careful when using it though.
int duration = ParametersHelper.getDuration()!; // using the ! operator
Future.delayed(const Duration(milliseconds: duration));
The second option is to use the ?? operator which means if the value is null assign another value
int duration = ParametersHelper.getDuration() ?? 2; // if null assign 2
Future.delayed(const Duration(milliseconds: duration));
CodePudding user response:
You can write like this :
int? duration = ParametersHelper.getDuration();
Future.delayed( Duration(milliseconds: duration!));
as you can write null assertion operator (!)
CodePudding user response:
'int?' means that the value can be either int or null. SharedPreferences returns 'int?' in
_pref.getInt("Duration")
because in case there is no value with key "Duration" stored with
_pref.setInt("Duration", 4)
in that case it will return null.
If you are sure that there is a int stored in a key named "Duration" in SharedPreferences before calling getDuration() function, then you can use "!" (conditional property access operator) in dart.
int? duration = getDuration();
Future.delayed(Duration(milliseconds: duration!));
"!" is a dart operator for conversion from a nullable to a non-nullable type. Use it only if you are absolutely sure that the value will never be null, i.e. there is always a int stored in key "Duration" in preferences before calling it, and do not confuse it with the conditional property access operator(?).