如何在 Flutter 中的 no-activity 超时后调用方法?

How to call a method after a no-activity timeout in Flutter?

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

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

我还没有真正尝试过这个,但是根据我使用 flutter 的经验,

我想说您可以在小部件树的顶部创建一个手势检测器,只要用户点击屏幕,它就会捕获。

例如,您可以记录一个带有时间戳的 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();
  }

我知道这可能不是一个完美的例子,但希望能为您指明正确的道路!我没有时间做出更有力的回答,但想表达我的观点。

感谢作者在这个问题中的正确答案,因为我从他的回答中提取了继承的小部件示例