Search code examples
flutterdartflutter-packages

Counter and call duration combination in flutter


int score = 0;
score += 1;

I wish to add 1 (+= 1) to score when call duration reach 30 seconds just once and reset the score to 0 when call duration is less than 30 seconds.

Text('$score')

and show it like this

import 'package:permission_handler/permission_handler.dart';
import 'package:call_log/call_log.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';

I have imported 3 packages above

void callLogs() async {
  Iterable<CallLogEntry> entries = await CallLog.get();
  for (var item in entries) {
    print(Duration());   <--- Use Duration & if statement to solve but duration not printing
   }
 }

and code I wrote above is not working as I imagined to even start with. What changes can I make for adding and resetting score to work? Please help and thanks in advance


Solution

  • Your code waits for this call to complete so it never runs anything under it:

    Iterable<CallLogEntry> entries = await CallLog.get();
    

    You could use the StopWatch object to get the time:

    void callLogs() async {
    
        Stopwatch stopwatch = new Stopwatch()..start();
    
        Iterable<CallLogEntry> entries = await CallLog.get();
        for (var item in entries) {
            var duration = stopwatch.elapsed;
            print('Duration $duration');
       }
     }
    

    And use setState() to set score:

    setState(() { duration > 30 ? score += 1 : score = 0 });