Flutter | how can i record the time user spend in my app in flutter?

3.4k Views Asked by At

I have developed and app and the client want me to store the total time spend by the user inside the app how can I achieve that I have tried using this App_usage package in flutter but its showing me Star Activity error if you guys have any solution
please let me know thanks in advance :)

3

There are 3 best solutions below

5
On

Have some variable that tracks the start time and end/ pause time of the app and persist the difference. You will have to hook that up to the app lifecycle to listen to events such as pausing/ resuming the app. (e.g. How to handle onPause/onResume in Flutter App?)

Something like this:

class AppLifecycleReactor extends StatefulWidget {
  const AppLifecycleReactor({Key key}) : super(key: key);

  @override
  _AppLifecycleReactorState createState() => _AppLifecycleReactorState();
}

class _AppLifecycleReactorState extends State<AppLifecycleReactor>
    with WidgetsBindingObserver {
  DateTime startTime;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      startTime = DateTime.now();
    }

    if (state == AppLifecycleState.detached ||
        state == AppLifecycleState.paused) {
      var usageTime = DateTime.now().difference(startTime);
      // do whatever with the usageTime
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: MyContent(),
    );
  }
}
3
On
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(new HomePage());
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String? docId;

  addTime() async {
    docId = await TimeHomePageUsage.addUserStartTime();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    addTime();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    TimeHomePageUsage.addUserEndTime(docId);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Text('Home Page'),
      ),
    );
  }
}

class TimeHomePageUsage {
  static Future<String?> addUserStartTime() async {
    String? docId;
    await FirebaseFirestore.instance
        .collection('timeUsage')
        .add({'startTime': DateTime.now().toString()})
        .then((doc) => print("Start Time added ${docId = doc.id} "))
        .catchError((error) => print("Failed to add Start Time: $error"));
    return docId;
  }

  static Future<void> addUserEndTime(String? docId) async {
    await FirebaseFirestore.instance
        .collection('timeUsage')
        .doc(docId)
        .update({"endTime": DateTime.now().toString()})
        .then((value) => print("End Time added "))
        .catchError((error) => print("Failed to add End Time: $error"));
  }
}
2
On

like Chris Marx said, you can use the counter to store usage time. and to handle the sync operation to server, you can use shared preferenceq to store data and when the app launched again you do sync(update) with the server.