flutter_프로젝트/1_타이머_만들기

5. 기능 추가하기 - pause 기능 만들기

studyapps 2024. 7. 20. 23:10

앞에서 시작하고 나서 버튼을 바꿨으므로, 동일한 방법으로

pause기능을 구현해 보기로 한다.

 

그전에 Timer.periodic 을 변수로 지정을 먼저 한다.

(참고 -- 함수를 변수에 할당 (tistory.com))

 var ttotal = 100;
 Timer? _timer;
 bool isRunning = false;

 

이렇게 _timer 변수를 만들고 변수에 시간을 할당한다.

void start_btn() {
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      setState(() {
        isRunning = true;
        ttotal -= 1;
      });
    });
  }

 

이렇게 할당하면 _timer 변수를 이용해서 시간을 멈출 수 있다.

pause_btn 함수를 만들어서 isRunning 함수를 false로 바꿔주고 => 버튼 변경

_timer 를 캔슬 시킨다.

  void pause_btn() {
    setState(() {
      isRunning = false;
    });
    _timer?.cancel();
  }

 

이상한건 setState 함수가 필요 없을 것 같지만, isRunning변수값을 바꿔서 버튼을 변경하기 위해서는 (UI 에반영하기 위해서는) setState 안에 넣어여 한다.

 

이렇게 새로운 함수를 버튼에 연결해 준다. ? : (삼항 연산자) 이용해서 유사하게 연결한다.

  ElevatedButton(
    onPressed: isRunning ? pause_btn : start_btn,
    child: Text(isRunning ? 'Pause' : 'Start'),
  )

 

 

시작하면 버튼이 pause로, 바뀐 버튼을 누르면 정상적으로 멈춘다.

 

<소스코드>

 

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

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const stopWatch(),
    );
  }
}

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

  @override
  State<stopWatch> createState() => _stopWatchState();
}

class _stopWatchState extends State<stopWatch> {
  var ttotal = 100;
  Timer? _timer;
  bool isRunning = false;

  void start_btn() {
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      setState(() {
        isRunning = true;
        ttotal -= 1;
      });
    });
  }

  void pause_btn() {
    setState(() {
      isRunning = false;
    });
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('StopWatch'),
        centerTitle: true,
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Column(
            // mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const SizedBox(
                height: 100,
              ),
              Container(
                  height: 200,
                  width: 200,
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(100)),
                    color: Colors.amber,
                  ),
                  child: Center(
                    child: Text(
                      '$ttotal',
                      style: const TextStyle(
                        fontSize: 40,
                        color: Colors.white,
                      ),
                    ),
                  )),
              const SizedBox(
                height: 30,
              ),
              ElevatedButton(
                onPressed: isRunning ? pause_btn : start_btn,
                child: Text(isRunning ? 'Pause' : 'Start'),
              )
            ],
          )
        ],
      ),
    );
  }
}