skip to Main Content

I want to calculate every pages stay duration of my flutter app. The stay duration means from page becomes visible to page hide.

How do i do this?

Any idea might help me.

2

Answers


  1. An idea would be to capture the time at initState for stateful widgets, or under build method for stateless widgets, and compare it with the time on leave, as follows:

      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");
        }
      }
    

    To learn how to detect when the user moves away from the current page take a look at this answer:

    Detect if the user leaves the current page in Flutter?

    Login or Signup to reply.
  2. You can use this wrapper widget,

    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;
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search