美文网首页
flutter_定时器和前后台

flutter_定时器和前后台

作者: ChaosHeart | 来源:发表于2020-12-10 11:26 被阅读0次
    ///Widget
    class AirCompressorPage extends StatefulWidget {
      @override
      _AirCompressorPageState createState() => _AirCompressorPageState();
    }
    
    ///State
    class _AirCompressorPageState extends BaseState<AirCompressorPage>
        with WidgetsBindingObserver {
    
     ///initState
      @override
      void initState() {
        super.initState();
        //监听生命周期
        WidgetsBinding.instance.addObserver(this);
        //定时器
        _initTimer();
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        print("--" + state.toString());
        switch (state) {
          case AppLifecycleState.inactive: // 应用程序可见,不可操作。
            break;
          case AppLifecycleState.resumed: // 应用程序可见,可操作, 前台
            _initTimer(); //创建并开启定时器
            break;
          case AppLifecycleState.paused: // 应用程序不可见,不可操作, 后台
            _cancelTimer(); //取消并销毁定时器
            break;
          case AppLifecycleState.detached: //  虽然还在运行,但已经没有任何存在的界面。
            break;
        }
      }
    
      ///dispose
      @override
      void dispose() {
        //销毁监听生命周期
        WidgetsBinding.instance.removeObserver(this);
        //取消定时器
        _cancelTimer();
        super.dispose();
      }
    
    ///build
      @override
      Widget build(BuildContext context) {
             return Stack();
    }
    
    //定时器
      Timer _timer;
    
      ///定时器 - 1分钟
      void _initTimer() {
        if (_timer == null) {
          _timer = Timer.periodic(Duration(minutes: 1), (timer) {
             print("定时器里面的方法");
            } else {
              print("定时器-不符合请求要求");
            }
          });
        }
      }
    
      ///取消定时器
      void _cancelTimer() {
        if (_timer != null) {
          _timer.cancel();
          _timer = null;
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:flutter_定时器和前后台

          本文链接:https://www.haomeiwen.com/subject/cfafgktx.html