【问题标题】:How to calculate the time a widget is in view in flutter如何计算小部件在颤动中的显示时间
【发布时间】:2019-06-16 01:10:58
【问题描述】:

来自 Android 背景,我可以计算 onPauseonResume 中的时间并将它们彼此分开。我将如何使用颤振来做到这一点。我可以在initState 中获取时间,但不确定当小部件消失时要调用什么方法。我正在使用DateTime 类来计算时间。我有正确的方法吗?或者...我的用例是我想奖励停留在屏幕上的用户。

【问题讨论】:

标签: flutter


【解决方案1】:

您可以获得导航到另一个widger之前和之后的时间:

    ElevatedButton(
          child: Text('Second'),
          onPressed: () {
            print('First out: ${DateTime.now()}');
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondView()),
            ).then(
              (value) => print('First in: ${DateTime.now()}'),
            );
          },
        ),

或者(对于 StateFull)在 InitState() 和 Dispose() 上获取时间,但在 dispose() 上获取时间可能会有延迟。取决于您需要的精度:

  @override
  void initState() {
    super.initState();
    print('Second in: ${DateTime.now()}');
  }


  @override
  void dispose() {
    print('Second out: ${DateTime.now()}');
    super.dispose();    
  }

【讨论】:

    猜你喜欢
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2021-11-26
    • 2019-10-27
    • 2019-03-19
    • 2021-01-22
    • 2021-07-13
    相关资源
    最近更新 更多