首页 > 解决方案 > Flutter 如何处理基于时间的事件?

问题描述

我在颤振中有一个小部件,可以通过观看奖励视频来消除它。但我不希望小部件被完全解雇。说3天。

因此,如果用户点击特定小部件,则广告将被禁用 3 天。有可能吗?有人可以帮助我提供参考资料或想法来完成这项工作吗?

请帮忙

标签: flutterdart

解决方案


一、获取共享首选项包,使本地存储跟踪日期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"),
                  ),
                ),
              )
          ],
        ),
      ),

推荐阅读