转换int? flutter
我得到INT?带有getInt()方法的共享preferences类的变量。 我必须放这个int?作为持续时间对象的参数,但我需要有一个int。 我能做些什么? 这是代码:
int? duration = ParametersHelper.getDuration();
Future.delayed(const Duration(milliseconds: duration));
这是parametershelper中的getDuration()方法:
static int? getDuration() {
return _pref.getInt("Duration");
}
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过明确告诉DART编译器来覆盖此行为,尽管该变量可能是可确定的,但我保证它不是无效的,但是使用时要小心。
第二种选择是使用?运算符,这意味着如果值为null分配另一个值
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.
The second option is to use the ?? operator which means if the value is null assign another value
您可以这样写:
因为您可以编写
null断言操作员(!)
You can write like this :
as you can write
null assertion operator (!)
'int?''意味着该值可以是int或null。共享流程返回“ int?”因为
,如果没有键“持续时间”的值,
在这种情况下,它将返回null。
如果您确定在调用getDuration()函数之前,在sharedPreferences中名为“持续时间”的密钥中存储一个int,则可以使用“!” (有条件的属性访问操作员)在飞镖中。
“!”是从可将其转换为无效类型的DART运算符。
仅当您绝对确定该值永远不会为null时使用它,即在调用它之前,总有一个键“持续时间”中的int存储,并且不要将其与条件属性访问操作员(?)混淆。
'int?' means that the value can be either int or null. SharedPreferences returns 'int?' in
because in case there is no value with key "Duration" stored with
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.
"!" 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(?).