Spicy Pumpkin
Spicy Pumpkin

Reputation: 133

How do I initiate a stopwatch when the user taps a button?

I am trying to integrate a stopwatch into my app. I am new to flutter, so I am not quite able to do this. I have a screen with a container containing a TextButton(), what I want is that when the user presses this TextButton(), a stopwatch will start (starting from 00:00, and counting upwards). When the user presses this button again, I want the stopwatch to stop and display however much time has elapsed. Here is my code so far:

import 'dart:async';
import 'Stopwatch.dart';
 import 'package:flutter/material.dart';

 class TimerScreen extends StatelessWidget {
 const TimerScreen({super.key});

 @override
 Widget build(BuildContext context) {
   return Scaffold(
  appBar: AppBar(
    // backgroundColor: Colors.teal,
    title: const Text(
      'Trainer',
      style: TextStyle(color: Colors.deepOrangeAccent),
    ),
    actions: [
      IconButton(
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              actions: [
                Center(
                  child: TextButton(
                    onPressed: () {},
                    child: Text('2'),
                  ),
                ),
                Center(
                  child: TextButton(
                    onPressed: () {},
                    child: Text('3'),
                  ),
                ),
              ],
              title: Text('Choose algset:'),
            ),
          );
        },
        icon: const Icon(
          Icons.add_circle_outline,
          color: Colors.deepOrangeAccent,
        ),
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
      ),
    ],
  ),

  body: Column(
    children: [
      Container(
        height: 60,
        width: double.infinity,
        child: const Center(
          child: Text(
            "Testing",
            style: TextStyle(fontSize: 25),
          ),
        ),
      ),
      const SizedBox(height: 10),
      Container(
        height: 665,
        width: double.infinity,
        child: Center(
          child: Padding(
            padding: const EdgeInsets.only(bottom: 145.0),
            child: TextButton(
              onPressed: () {//THIS IS WHERE I NEED A STOPWATCH
               
              },
              child: Text(
                '00:00',
                style: TextStyle(fontSize: 50, color: Colors.white),
              ),
            ),
          ),
        ),
      )

I’ve tried using the Stopwatch() class, with the help of flutter docs, but the docs were not of much use, so I am not very sure on how to use this class. I’ve tried looking at other people’s posts, but they weren’t quite what I wanted. Any help is appreciated!

Upvotes: 0

Views: 73

Answers (1)

rasityilmaz
rasityilmaz

Reputation: 1399

class StopWatchWidget extends StatefulWidget {
  const StopWatchWidget({super.key});

  @override
  State<StopWatchWidget> createState() => _StopWatchWidgetState();
}

class _StopWatchWidgetState extends State<StopWatchWidget> {
  final Stopwatch _stopwatch = Stopwatch();
  String stopWatchText = '00:00';
  void startStopWatch() {
    if (_stopwatch.isRunning) {
      _stopwatch.stop();
    } else {
      stopWatchText = '00:00';
      _stopwatch
        ..reset()
        ..start();
    }

    Timer.periodic(const Duration(milliseconds: 1), (timer) {
      setState(() {
        if (!_stopwatch.isRunning) {
          timer.cancel();
        }
        stopWatchText = '${(_stopwatch.elapsed.inMinutes % 60).toString().padLeft(2, '0')}:${(_stopwatch.elapsed.inSeconds % 60).toString().padLeft(2, '0')}';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: TextButton(
              onPressed: startStopWatch,
              child: Text(
                stopWatchText,
                style: const TextStyle(fontSize: 50, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Upvotes: 0

Related Questions