flutter - Flutter 如何处理基于时间的事件?
问题描述
我在颤振中有一个小部件,可以通过观看奖励视频来消除它。但我不希望小部件被完全解雇。说3天。
因此,如果用户点击特定小部件,则广告将被禁用 3 天。有可能吗?有人可以帮助我提供参考资料或想法来完成这项工作吗?
请帮忙
解决方案
一、获取共享首选项包,使本地存储跟踪日期shared_preferences: ^2.0.5
像这样制作本地存储 -
import 'package:shared_preferences/shared_preferences.dart';
class SetUserLocalStorage {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
void date(String valueOfDate) async {
final SharedPreferences prefs = await _prefs;
prefs.setString(UserStorageKey().valueOfDate, valueOfDate);
}
void clear() async { // For Your Further Operation, If needed
final SharedPreferences prefs = await _prefs;
prefs.clear();
}
}
class GetUserLocalStorage {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<String> date() async {
final SharedPreferences prefs = await _prefs;
return prefs.getString(UserStorageKey().valueOfDate);
}
}
class UserStorageKey {
String get valueOfDate => "valueOfDate";
}
现在,在您的页面/屏幕中,定义变量 -
bool _showTheAd = false;
DateTime _now = DateTime.now();
DateTime _date = DateTime.now();
并在 InitState 中,开始根据时间检查条件,我将其分为三部分以便更好地理解
@override
void initState() {
super.initState();
_initialPoint();
}
在_initialPoint()
-
void _initialPoint() async {
await GetUserLocalStorage().date().then((value) {
setState(() {
_date = DateTime.parse(value);
});
}).then((value) {
_conditionCheck();
});
}
在_conditionCheck -
void _conditionCheck() {
if (_date == null) {
setState(() {
_showTheAd = true;
});
} else {
setState(() {
_now = DateTime.now();
});
if (_now.isAfter(_date)) {
setState(() {
_showTheAd = true;
});
}
}
}
我知道,这些就像“脏代码”,但我认为这将帮助您理解场景。在正文中,根据 _showTheAd 条件显示添加,并使用一些拦截器/侦听器来感知视频何时结束,我正在使用墨水池,并在onTap()
完整场景中执行代码 -
Container(
child: Column(
children: [
if (_showTheAd)
InkWell(
onTap: () {
setState(
() {
_date = _now.add(
Duration(seconds: 5),
); // to add Date _now.add(Duration(days:3));
},
);
SetUserLocalStorage().date(_date.toIso8601String());
},
child: Center(
child: Container(
height: 120,
width: 120,
color: Colors.red,
child: Text("the ad"),
),
),
)
],
),
),
推荐阅读
- java - 我如何检查用户输入是否不是java中的字符串
- html - 居中 HTML 元素
- statistics - 投掷 10 次硬币的参数估计
- javascript - 使用分页显示每页五个帖子不起作用
- python - Python - Pandas 在不编辑索引的情况下找到最后一个可用行
- typescript - 基于数据集构建对象[]
- swift - 将pytorch转换为torchscript后结果不同?将 NSnumber 转换为 Float 会导致任何损失吗?
- gulp - 升级到 gulp 4 后 gulp watch 出现问题
- typescript - 打字稿中函数定义之前的声明键是什么?
- yocto - 在 qemu 中运行 Raspberry Pi Zero W 映像