4

Coming from an Android background, I could calculate the time in the onPause and onResume and take them away from each other. How would I do this using flutter. I can get the time in the initState but not sure what method to call when the widget goes out of view. I'm using the DateTime class to calculate the time. Have I the right approach? Or...My use case is I want to reward a user staying on a screen.

flutter
  • 6,188
  • 9
  • 45
  • 78

1 Answers1

0

You could get the time before and after navigating to the other 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()}'),
            );
          },
        ),

Or (for StateFull) get the time on InitState() and on Dispose(), but there may be an delay when getting the time on dispose(). Depends on the precision that you need:

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


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