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.
Asked
Active
Viewed 1,476 times
4

flutter
- 6,188
- 9
- 45
- 78
-
For what purpose would you need that? – Günter Zöchbauer Jan 22 '19 at 14:27
-
sorry just added – flutter Jan 22 '19 at 14:28
-
need to find time spent on screen – flutter Jan 22 '19 at 14:28
-
1Would you not rather want to know if the application is in the foreground and/or if a specific route is active? – Günter Zöchbauer Jan 22 '19 at 14:28
-
a specific route...I want to reward as user for staying on a screen(watching a video) – flutter Jan 22 '19 at 14:29
-
2https://stackoverflow.com/questions/49869873/flutter-update-widgets-on-resume/49870276#49870276 for app lifecycle and https://docs.flutter.io/flutter/widgets/RouteObserver-class.html for route – Günter Zöchbauer Jan 22 '19 at 14:30
1 Answers
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();
}

Fabio Campos
- 76
- 6