Flutter timer的使用

timer在實際的項目開發(fā)中用的不是很多,但是對于一些訂單的頁面還是會用的到,網(wǎng)上關于timer的資料不是很多,對于一些復雜的使用場景沒有提到.此文根據(jù)在實際項目中的使用整理了一個demo.再此開源,純屬技術交流,歡迎評論交流.
先展示一下最終的實現(xiàn)效果
最終實現(xiàn)效果

實現(xiàn)思路:
實現(xiàn)思路就是界面里面使用一個定時器,然后在倒計時里對數(shù)據(jù)源里面的時間字段就行減一操作,再刷新界面就可以了,思路很簡單.但是定時器廢了勁了.

遇到問題:

下拉刷新定時器加速問題

問題代碼:

class TimerPage extends StatefulWidget {
  const TimerPage({Key? key}) : super(key: key);

  @override
  State<TimerPage> createState() => _TimerPageState();
}

class _TimerPageState extends State<TimerPage> {
  late Timer _timer;
  List dataList = [
    500,
    620,
    700,
    820,
    960,
    180,
    200,
    220,
  ];
  late EasyRefreshController _controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController(
    );
    creatData();
  }

  void creatData() {
    var date = DateTime.parse("2022-11-10 21:20:41");
    var today = DateTime.now();
    var difference = date.difference(today);
    int timeCount = difference.inSeconds;
    dataList.insert(0, timeCount);
    startTimer();
  }

  void startTimer() {
    // _timer.cancel();
    // _timer = null;
    List list = dataList;
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      for (int i = 0; i < list.length; i++) {
        var tempTime = list[i];
        if (tempTime == 0) {
        } else {
          tempTime -= 1;
        }
        list[i] = tempTime;
      }
      print('哈哈哈哈哈哈哈');
      setState(() {
        dataList = list;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    /// 寫一個下拉刷新的列表 定時器加速問題
    return Scaffold(
      appBar: AppBar(
        title: const Text('定時器使用'),
      ),
      body: EasyRefresh(
        controller: _controller,
        firstRefresh: false,
        header: ClassicalHeader(),
        footer: ClassicalFooter(),
        onRefresh: () async {
          await Future.delayed(const Duration(seconds: 1));
          creatData();
          _controller.resetLoadState();
        },
        child: ListView.builder(
            shrinkWrap: true,
            physics: const AlwaysScrollableScrollPhysics(),
            itemCount: dataList.length,
            itemBuilder: (BuildContext context, int index) {
              return Container(
                height: 50,
                alignment: Alignment.center,
                margin: const EdgeInsets.only(left: 15, right: 15, top: 15),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(6),
                    boxShadow: const [
                      BoxShadow(
                          color: Colors.black12,
                          offset: Offset(0.0, 0.0), //陰影xy軸偏移量
                          blurRadius: 2.0, //陰影模糊程度
                          spreadRadius: 2.0 //陰影擴散程度
                      )
                    ]),
                child: Text(
                  FormatUtils.constructTime(dataList[index]),
                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                ),
              );
            }),
      )
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer.cancel();
    // _timer = null;
    _controller.dispose();
  }
}

late關鍵字顯式聲明一個非空的變量,但不初始化。
如果不加late關鍵字,類實例化時此值是不確定的,無法通過靜態(tài)檢查,加上late關鍵字可以通過靜態(tài)檢查,但由此會帶來運行時風險。但是我在下拉刷新的時候timer又重新創(chuàng)建了一個,所以就出現(xiàn)了定時器的加速的問題.我在定時器里面打印了內容,發(fā)現(xiàn)下拉刷新一次之后,打印的內容是兩個兩個打印的,在退出當前頁面以后還有一個定時器在打印.所以,一開始我就在startTimer方法里添加了_timer.cancel()這行代碼,發(fā)現(xiàn)timer停止了,一個都不走了.我當時思考給timer加一個final,修改代碼如下'_timer@484517720' has already been initialized.就可以解決這個問題,結果下拉刷新時報錯了_timer@484517720' has already been initialized.提示timer對象已經(jīng)存在了,不能重復創(chuàng)建.是因為final 表示單分配,最終變量或字段必須具有初始化程序。一旦分配了值,最終變量的值就無法更改。
最后又經(jīng)過了一番嘗試,終于解決了這個問題,先上代碼.

class TimerPage extends StatefulWidget {
  const TimerPage({Key? key}) : super(key: key);

  @override
  State<TimerPage> createState() => _TimerPageState();
}

class _TimerPageState extends State<TimerPage> {
  Timer? _timer;
  List dataList = [
    500,
    620,
    700,
    820,
    960,
    180,
    200,
    220,
  ];
  late EasyRefreshController _controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController(
    );
  }

  void creatData() {
    var date = DateTime.parse("2022-11-10 21:20:41");
    var today = DateTime.now();
    var difference = date.difference(today);
    int timeCount = difference.inSeconds;
    dataList.insert(0, timeCount);
    startTimer();
  }

  void startTimer() {
    _timer?.cancel();
    _timer = null;
    List list = dataList;
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      for (int i = 0; i < list.length; i++) {
        var tempTime = list[i];
        if (tempTime == 0) {
        } else {
          tempTime -= 1;
        }
        list[i] = tempTime;
      }
      print('哈哈哈哈哈哈哈');
      setState(() {
        dataList = list;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    /// 寫一個下拉刷新的列表 定時器加速問題
    return Scaffold(
      appBar: AppBar(
        title: const Text('定時器使用'),
      ),
      body: EasyRefresh(
        controller: _controller,
        firstRefresh: true,
        header: ClassicalHeader(),
        footer: ClassicalFooter(),
        onRefresh: () async {
          await Future.delayed(const Duration(seconds: 1));
          creatData();
          _controller.resetLoadState();
        },
        child: ListView.builder(
            shrinkWrap: true,
            physics: const AlwaysScrollableScrollPhysics(),
            itemCount: dataList.length,
            itemBuilder: (BuildContext context, int index) {
              return Container(
                height: 50,
                alignment: Alignment.center,
                margin: const EdgeInsets.only(left: 15, right: 15, top: 15),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(6),
                    boxShadow: const [
                      BoxShadow(
                          color: Colors.black12,
                          offset: Offset(0.0, 0.0), //陰影xy軸偏移量
                          blurRadius: 2.0, //陰影模糊程度
                          spreadRadius: 2.0 //陰影擴散程度
                      )
                    ]),
                child: Text(
                  FormatUtils.constructTime(dataList[index]),
                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                ),
              );
            }),
      )
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer?.cancel();
    _timer = null;
    _controller.dispose();
  }
}

其實就是聲明timer時,這樣聲明Timer? _timer;startTimer中將上一個timer取消,并置為null,再重新創(chuàng)建一個timer,就解決了這個問題.

注意點

一定要記住在dispose中加上下面的代碼,不然的話定時器是不會釋放,容易引起內存的問題.

@override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer?.cancel();
    _timer = null;
    _controller.dispose();
  }

到此我們就可以很愉快的使用定時器了,純屬技術交流,不喜勿噴,歡迎評論交流.

demo地址請移步: 項目地址
Flutter TabBar 在實際項目中的運用: 項目地址
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容