【问题标题】:How to call a method after a no-activity timeout in Flutter?如何在 Flutter 中无活动超时后调用方法?
【发布时间】:2019-10-26 11:44:57
【问题描述】:

实现以下功能的最佳方式是什么:

在用户上次与应用交互后等待指定时间量(由常量变量定义)后,自动调用一个函数以向页面添加几个小部件。

【问题讨论】:

  • 你等了多久?
  • @jits619 就我而言,可能是 1 到 10 秒。但我正在寻找一种可以随时使用的方法。
  • 您能否添加有问题的日志,请添加有关您如何获得无活动超时的详细说明。
  • @jits619 这是功能请求,而不是错误报告。超时是指每次用户与应用交互时禁用的异步计时器;每次用户不与应用程序交互时,它都应该开始滴答作响,并且应该在 x 时间过去后调用一个方法。有意义吗?

标签: user-interface flutter triggers timeout flutter-layout


【解决方案1】:

我还没有真正尝试过,但是根据我使用颤振的经验,

我想说您可以在小部件树的顶部创建一个手势检测器,该检测器将在用户点击屏幕时进行捕捉。

例如,您可以记录一个带有时间戳的 int 并在继承的小部件中更新此值(可能必须在手势检测器之上)

最后,任何需要监听的小部件都可以有一个计时器,该计时器每隔 x 时间检查一次时间,并比较是否在 1 到 10 秒之前进行了触摸。

继承的小部件可能是这样的:

class MyInherited extends StatefulWidget {
  static MyInheritedData of(BuildContext context) =>
      context.inheritFromWidgetOfExactType(MyInheritedData) as MyInheritedData;

  const MyInherited({Key key, this.child}) : super(key: key);

  final Widget child;

  @override
  _MyInheritedState createState() => _MyInheritedState();
}
class _MyInheritedState extends State<MyInherited> {
  String myField;

  void onMyFieldChange(String newValue) {
      myField = newValue;
  }

  @override
  Widget build(BuildContext context) {
    return MyInheritedData(
      myField: myField,
      onMyFieldChange: onMyFieldChange,
      child: widget.child,
    );
  }
}

class MyInheritedData extends InheritedWidget {
  final String myField;
  final ValueChanged<String> onMyFieldChange;

  MyInheritedData({
    Key key,
    this.myField,
    this.onMyFieldChange,
    Widget child,
  }) : super(key: key, child: child);

  @override
  bool updateShouldNotify(MyInheritedData oldWidget) {
    return oldWidget.myField != myField ||
        oldWidget.onMyFieldChange != onMyFieldChange;
  }
}

小部件树的顶部看起来像这样:

GestureDetector(
  onTap: (){
    // Update the value of your field
  }

最后,当你需要监听这个变化时,你可以像这样添加一个计时器:

  Timer timer;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      timer = Timer.periodic(Duration(seconds: 10), (Timer t) {
        // Get your inherited widget here and check the value, compare it and act as you pleased
      });
    });
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

我知道这可能不是一个完美的例子,但希望你能找到正确的道路!我没有时间做出更强有力的答案,但想发表我的观点。

感谢作者在这个问题中的正确答案,因为我从他的回复 Flutter: How to correctly use an Inherited Widget? 中获取了继承的小部件示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多