flutterでsettimeout

投稿者:

n秒後に何かしたい

こんなページがあるとして、ボタンを押したn秒後に文言を変えたい

ソース

class _TestPageState extends State<ResultPage> {

  String _titleText = "test";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(_titleText, style: TextStyle(fontSize: 50)),
            ElevatedButton(
              onPressed: (){

              },
              child: const Text("push!")
            )
          ],
        ),
      ),
    );
  }
}

Timerを使う

https://api.dart.dev/stable/2.13.4/dart-async/Timer-class.html

dart:asyncをimportして、ソースを以下のように変える

引数のDurationで間隔を設定できますが、秒だけじゃなくて色々設定できて便利ですねぇ

https://api.dart.dev/stable/2.13.4/dart-core/Duration-class.html

import 'dart:async';

class _TestPageState extends State<ResultPage> {

  String _titleText = "test";

  void _changeTitle() {
    setState(() {
      _titleText = "oops";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(_titleText, style: TextStyle(fontSize: 50)),
            ElevatedButton(
              onPressed: (){
                Timer(const Duration(seconds: 3), _changeTitle);
              },
              child: const Text("push!")
            )
          ],
        ),
      ),
    );
  }
}

3秒後に切り替わるゥ〜〜┏( ◜◡~)┛.┏( ◜◡~)┛.┏( ◜◡~)┛.┏( ◜◡~)┛.

setIntervalみたいにしたいんだが?(n秒間隔で処理)

じゃぁボタンを押したら1秒毎にテキスト変えてみましょう

Timer.periodicを使います

https://api.dart.dev/stable/2.14.3/dart-async/Timer/Timer.periodic.html

class _TestPageState extends State<ResultPage> {

  int _counter = 0;

  Timer? _timer;

  void _cancelTimer() {
    if (_timer != null) {
      _timer!.cancel();
    }
  }

  @override
  void dispose(){
    _cancelTimer();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(_counter.toString(), style: TextStyle(fontSize: 50)),
            ElevatedButton(
              onPressed: (){
                _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
                  setState(() {
                    _counter++;
                  });
                });
              },
                child: const Text("push!")
                
            ),
            ElevatedButton(
                onPressed: (){
                  _cancelTimer();
                },
                child: const Text("stop!")
            )
          ],
        ),
      ),
    );
  }
}

    

これで「push」を押したら1秒毎にテキストが代わりますね

「stop」を押したら止まります

periodicはずっと動き続けてしまうのでちゃんとcancelする必要があるっぽいので気をつけてください

↓参考↓

https://qiita.com/ywand/items/9df5cc894bae594d5181

https://scrapbox.io/dennougorilla/Timer.periodic%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6