반응형
Flutter 플러터 타이머 간단 구현
코드 작성
import 'dart:async';
import 'package:flutter/material.dart';
class TimerPage extends StatefulWidget {
const TimerPage({Key? key}) : super(key: key);
@override
State<TimerPage> createState() => _TimerPageState();
}
class _TimerPageState extends State<TimerPage> {
int _seconds = 0;
bool _isRunning = false;
late Timer _timer;
void _startTimer() {
_isRunning = true;
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
_seconds++;
});
});
}
void _stopTimer() {
_isRunning = false;
_timer.cancel();
}
void _resetTimer() {
setState(() {
_seconds = 0;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('$_seconds', style: TextStyle(fontSize: 72)),
SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _isRunning ? null : _startTimer,
child: Text('Start'),
),
SizedBox(width: 16),
ElevatedButton(
onPressed: _isRunning ? _stopTimer : null,
child: Text('Stop'),
),
SizedBox(width: 16),
ElevatedButton(
onPressed: _resetTimer,
child: Text('Reset'),
),
],
),
],
),
),
);
}
}
참고할만한 글
블로그 운영자가 만든 모바일 게임 다운 해보기
반응형