Search code examples
flutterdarttimerstopwatch

Flutter count time to complete task in background


Trying to run a timer in the background to show user how long it took them to complete quiz on the results page.

I have tried using Stopwatch using code below but am getting error that 'start' was called on null.

  class CardPage extends StatefulWidget {
  static const String id = 'card_page';

  final List<File> favpicz;
  final timer = Stopwatch();

  CardPage({@required this.favpicz});

  @override
  _CardPageState createState() => _CardPageState(favpicz);
}

class _CardPageState extends State<CardPage> with TickerProviderStateMixin {
//animation controllers

  List<File> favpicz;
  Stopwatch timer;

  _CardPageState(this.favpicz);

  @override
  void initState() {
    super.initState();
    timer.start();
  }

  @override
  void dispose() {
    if (timer != null) {
      timer.stop();
      timer = null;
    }
super.dispose();
  }

As you can see here I would like to start the timer when the user arrives at the quiz screen. Then I would like to call timer.stop() on a function that transitions to the results page.

On the results page I would like to express the time as a Text widget in the format ex. 3:57

Stopwatch doesn't seem right for this and most of my timer searches have been for countdown timers or stop watch apps on the screen using Streams which is unnecessary for this purpose. Help is much appreciated to find a package or class that counts up rather than down.


Solution

  • Initialize timer inside initState() :

    @override
      void initState() {
        super.initState();
        timer = Stopwatch();
        timer.start();
      }
    

    Also remove timer from your Stateful class :

    class CardPage extends StatefulWidget {
      static const String id = 'card_page';
    
      final List<File> favpicz;
      final timer = Stopwatch(); // remove this
    
      CardPage({@required this.favpicz});
    
      @override
      _CardPageState createState() => _CardPageState(favpicz);
    }