在Flutter中如何计算页面停留时间?

nbnkbykc  于 2023-02-13  发布在  Flutter
关注(0)|答案(2)|浏览(296)

我想计算我的Flutter应用程序的每一页停留时间。停留时间意味着从页面变得可见到页面隐藏。
我该怎么做呢?
任何想法都可能帮到我。

cbjzeqam

cbjzeqam1#

您可以使用这个 Package 器小部件,

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: PageView.builder(
          itemCount: 4,
          itemBuilder: (context, index) => TrackWidgetLifeTime(
            child: Text("$index"),
            lifeTime: (spent) {
              log("I've spend ${spent.toString()}");
            },
          ),
        ),
      ),
    );
  }
}

class TrackWidgetLifeTime extends StatefulWidget {
  const TrackWidgetLifeTime({super.key, this.lifeTime, required this.child});
  final Function(Duration spent)? lifeTime;

  final Widget child;

  @override
  State<TrackWidgetLifeTime> createState() => _TrackWidgetLifeTimeState();
}

class _TrackWidgetLifeTimeState extends State<TrackWidgetLifeTime> {
  var stopwatch = Stopwatch();
  @override
  void initState() {
    super.initState();
    stopwatch.start();
  }

  @override
  void dispose() {
    if (widget.lifeTime != null) widget.lifeTime!(stopwatch.elapsed);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
voase2hg

voase2hg2#

一个想法是在initState(对于有状态小部件)或build方法(对于无状态小部件)下捕获时间,并将其与休假时间进行比较,如下所示:

late DateTime started;
  DateTime? ended;

  @override
  void initState() {
    started = DateTime.now();
    super.initState();
  }

  void onLeave() {
    ended = DateTime.now();
    if (ended != null) {
      var lapse = Duration(microseconds: ended!.microsecondsSinceEpoch-started.microsecondsSinceEpoch);
      print("Viewed page ${lapse.inSeconds} seconds");
    }
  }

要了解如何检测用户何时离开当前页面,请查看以下答案:
Detect if the user leaves the current page in Flutter?

相关问题