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

3. 화면에 표시하기

studyapps 2024. 7. 19. 18:22

ttotal 이라는 변수를 만들어서 100을 할당한다.

 

버튼이 눌리면 실행되는 함수에서 매 1초마다 ttotal에서 1씩 빼준다.

class _stopWatchState extends State<stopWatch> {
  var ttotal = 100;

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

 

컨테이너 안에 숫자도 ttotal로 바꿔준다.

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,
                      ),                    ),                  )),

 

결과는 디버그 창에서 확인 가능하다

 

어라 그런데 실행창에서는 변화가 없다.

왜 움지직이지 않니...

 

함수에서 숫자를 빼주는 (변화하는) 값을 setstate 안에 넣어줘야 한다.

(복잡한 설명들이 있지만...일단 난 이렇게 이해함)

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

 

이렇게 수정 해 주면 화면이 아름답게 변하는 것을 볼 수 있다.

움직인다.