5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Flutter]一番シンプルなカウントダウンタイマーの作り方

Last updated at Posted at 2020-05-18

はじめに

quiver.asyncライブラリのCountDownTimerクラスを利用して、シンプルなカウントダウンタイマーを実装してみました。

完成図

時間が余ったので、カウントダウンに合わせて小さくなるピーターパン症候群のおじさんもつけました。
画面収録 2020-05-19 0.13.57.mov.gif

参考サイト

実装

main.dart
import 'package:flutter/material.dart';
import 'package:quiver/async.dart'; // ①quiver.asyncライブラリを利用

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Countdown',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // ②カウントを示すインスタンス変数
  int _start = 10;
  int _current = 10;

  // ③ カウントダウン処理を行う関数を定義
  void startTimer() {
    CountdownTimer countDownTimer = new CountdownTimer(
      new Duration(seconds: _start), //初期値
      new Duration(seconds: 1), // 減らす幅
    );

    var sub = countDownTimer.listen(null);
    sub.onData((duration) {
      setState(() {
        _current = _start - duration.elapsed.inSeconds; //毎秒減らしていく
      });
    });

    // ④終了時の処理
    sub.onDone(() {
      print("Done");
      sub.cancel();
      _current = 10;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // ⑤現在のカウントを表示
            Text(
              "$_current秒",
              style: Theme.of(context).textTheme.display1,
            ),
            // ⑥カウントに合わせて小さくなるおじさんを表示
            Container(
              child: Image.network(
                'https://3.bp.blogspot.com/-QxAapI2H1Pk/VhSAsJpLPhI/AAAAAAAAzG0/80qjXfZlomk/s800/peterpan_syndrome.png',
                width: _current.toDouble() * 20,
                height: _current.toDouble() * 20,
              ),
            ),
            // ⑦カウントダウン関数を実行するボタン
            RaisedButton(
              onPressed: () {
                startTimer();
              },
              child: Text("start"),
            ),
          ],
        ),
      ),
    );
  }
}


5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?