[flutter] 플러터 커퍼티노 스테퍼를 이용한 카운트 다운 타이머 구현하기

이번 포스트에서는 플러터에서 커퍼티노 스테퍼를 이용하여 간단한 카운트 다운 타이머를 구현하는 방법에 대해 알아보겠습니다.

커퍼티노 스테퍼란?

커퍼티노 스테퍼는 iOS의 디자인 가이드 라인에 따라 디자인된 플러터 위젯 중 하나입니다. 스테퍼는 숫자 값을 증가 또는 감소시키는데 사용됩니다.

프로젝트 설정

먼저 새로운 플러터 프로젝트를 생성합니다. 아래 명령어를 사용하여 플러터 프로젝트를 생성할 수 있습니다.

flutter create countdown_timer

코드 구현하기

  1. lib/main.dart 파일을 열고 MyApp 클래스 안에 다음 코드를 추가합니다.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CountdownTimer(),
    );
  }
}
  1. lib/main.dart 파일을 열고 CountdownTimer 클래스를 정의하고 다음 코드를 추가합니다.
class CountdownTimer extends StatefulWidget {
  @override
  _CountdownTimerState createState() => _CountdownTimerState();
}

class _CountdownTimerState extends State<CountdownTimer> {
  int _countdownValue = 10;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Countdown Timer'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CupertinoTimerPicker(
              mode: CupertinoTimerPickerMode.hm,
              minuteInterval: 1,
              secondInterval: 1,
              initialTimerDuration: Duration(minutes: _countdownValue),
              onTimerDurationChanged: (Duration duration) {
                setState(() {
                  _countdownValue = duration.inMinutes;
                });
              },
            ),
            SizedBox(height: 20),
            Text(
              'Countdown: $_countdownValue minutes',
              style: TextStyle(fontSize: 20),
            ),
          ],
        ),
      ),
    );
  }
}
  1. 프로젝트를 실행합니다.
flutter run

코드 분석하기

결론

이제 플러터에서 커퍼티노 스테퍼를 이용하여 간단한 카운트 다운 타이머를 구현하는 방법을 알아보았습니다. 이를 활용하여 다양한 타이머 기능을 구현할 수 있습니다. 참고로, 이 코드는 플러터 2.0.0 버전에서 테스트되었습니다. 부족한 점이 있다면 Flutter 공식 문서를 참고하시기 바랍니다.

참고 자료: