title: Flutter: Continuously running stopwatch when switching screens
body: <p>I have a <code>stopwatch</code> widget which is called from the <code>Detailed Activity</code> page on one of my screens that starts when the page loads. How am I able to keep it continuously running in the background so that when I navigate from <code>Detailed Activity</code> to the <code>Home</code> page, I can display that same stopwatch's time?</p>
  
  <p>At the moment, the <code>Home</code> page displays the last saved time (into the variable). Instead I would like this to continue incrementing each second and vice versa switching between the two screens. I've tried adding the <code>startWatch()</code> and <code>initState()</code> method in my <code>Home</code> page, but don't know how to pass the stopwatch value while navigating to the <code>Detailed Activity</code> page</p>
  
  <p><a href="https://i.stack.imgur.com/DYQ5s.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DYQ5s.jpg" alt="enter image description here"></a>
  <a href="https://i.stack.imgur.com/m9aTW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m9aTW.jpg" alt="enter image description here"></a></p>
  
  <p>To clarify this more, my thinking was on the <code>Detailed Activity</code> page it is at e.g. 00:15:00 -> pass it into <code>Home</code> page and call initState() to automatically start the timer again. Would this work?</p>
  
  <p><strong>Timer.dart</strong></p>
  
  <pre><code>class NewStopWatch extends StatefulWidget {
  
    @override
    _NewStopWatchState createState() =&gt; new _NewStopWatchState();
  }
  
  class _NewStopWatchState extends State&lt;NewStopWatch&gt; {
  
    static _NewStopWatchState stopwatch;
    Stopwatch watch = new Stopwatch();
    Timer timer;
    bool startStop = true;
    static String elapsedTime = '';
    String duration;
  
    updateTime(Timer timer) {
      if (watch.isRunning) {
        setState(() {
          elapsedTime = transformMilliSeconds(watch.elapsedMilliseconds);
          User.getCurrentUser().getCurrentActivity().setElapsedTime(elapsedTime);
        });
      }
    }
  @override
    Widget build(BuildContext context) {
  
      return new Container(
              padding: EdgeInsets.all(20.0),
              child: new Column(
                children: &lt;Widget&gt;[
                  new Text(elapsedTime, style: new TextStyle(fontSize: 25.0)),
                  SizedBox(height: 20.0),
                  new Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: &lt;Widget&gt;[
                  FloatingActionButton(
                    heroTag: "btn1",
                    backgroundColor: Colors.red,
                    onPressed: () =&gt; startOrStop(),
                    child: Icon(Icons.pause)),
                  SizedBox(width: 20.0),
                  FloatingActionButton(
                    heroTag: "btn2",
                    backgroundColor: Colors.green,
                    onPressed: () =&gt; completeActivity(),
                    child: Icon(Icons.check)),
                    ],
                  )
                ],
              ));
    }
  
    void initState() {
      super.initState();
      WidgetsBinding.instance
          .addPostFrameCallback((_) =&gt; startWatch());
    }
  
    startOrStop() {
      if(startStop) {
        startWatch();
      } else {
        stopWatch();
      }
    }
  
    startWatch() {
      setState(() {
        startStop = false;
        watch.start();
        timer = Timer.periodic(Duration(milliseconds: 100), updateTime);
      });
    }
  
    stopWatch() {
      setState(() {
        startStop = true;
        watch.stop();
        setTime();
      });
    }
  
    resetWatch() {
      watch.reset();
      setTime();
    }
  
    setTime() {
      var timeSoFar = watch.elapsedMilliseconds;
      setState(() {
        elapsedTime = transformMilliSeconds(timeSoFar);
      });
    }
  
    completeActivity() { //do I call activity.stopActivity()?
      return showDialog(
            context: context,
            builder: (context) =&gt; new AlertDialog(
                  title: new Text('Complete Activity?',
                      style: new TextStyle(color: Colors.black, fontSize: 20.0)),
                  actions: &lt;Widget&gt;[
                    new FlatButton(
                      onPressed: () {
                        duration = elapsedTime;
                        print("Current activitiy: ${User.getCurrentUser().getCurrentActivity()}");
                        // User.getCurrentUser().completeActivity();
                        User.getCurrentUser().addPastActivity(User.getCurrentUser().getCurrentActivity());
                        User.getCurrentUser().getCurrentActivity().setStatus(ActivityStatus.completed);
                        User.getCurrentUser().setCurrentActivity(null);
                        Navigator.push(context, MaterialPageRoute(builder: (context) =&gt; FrontPage()));
                        // Navigator.popUntil(context, ModalRoute.withName("/"),);
                      },
                      child:
                          new Text('Yes', style: new TextStyle(fontSize: 18.0)),
                    ),
                    new FlatButton(
                      onPressed: () =&gt; Navigator.pop(context), // this line dismisses the dialog
                      child: new Text('No', style: new TextStyle(fontSize: 18.0)),
                    )
                  ],
                ),
          ) ??
          false;
      }
  
    transformMilliSeconds(int milliseconds) {
      int hundreds = (milliseconds / 10).truncate();
      int seconds = (hundreds / 100).truncate();
      int minutes = (seconds / 60).truncate();
      int hours = (minutes / 60).truncate();
  
      String hoursStr = (hours % 60).toString().padLeft(2, '0');
      String minutesStr = (minutes % 60).toString().padLeft(2, '0');
      String secondsStr = (seconds % 60).toString().padLeft(2, '0');
  
      return "$hoursStr:$minutesStr:$secondsStr";
    }
  
     static String getElapsedTime() {
      return elapsedTime;
    }
  }
  
  </code></pre>