【问题标题】:How to show a widget for some particular amount of time?如何在特定时间内显示小部件?
【发布时间】:2019-09-14 16:49:28
【问题描述】:

我在主屏幕上使用一个图标来向用户显示某个进程正在进行。我希望这个图标在某个特定时间(比如 100 秒)可见。用户可能会导航到不同的屏幕,但是当他回到主屏幕时,他应该能够看到图标,并且图标应该会在 100 秒后消失。我该怎么做?

【问题讨论】:

    标签: timer flutter


    【解决方案1】:
    class AnimatedFlutterLogo extends StatefulWidget {
      @override
      State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
    }
    
    class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
      Timer _timer;
      FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;
    
      _AnimatedFlutterLogoState() {
        _timer = new Timer(const Duration(milliseconds: 100), () {
          setState(() {
            _logoStyle = FlutterLogoStyle.horizontal;
          });
        });
      }
    
      @override
      void dispose() {
        super.dispose();
        _timer.cancel();
      }
    
      @override
      Widget build(BuildContext context) {
        return new FlutterLogo(
          size: 200.0,
          textColor: Palette.white,
          style: _logoStyle,
        );
      }
    }
    

    参考此链接How to run code after some delay in Flutter?

    您也可以使用以下代码来实现延迟状态更新:

    Future.delayed(const Duration(milliseconds: 100), () {
      setState(() {
        // Here you can write your code to update the state to show/hide the icon
      });
    });
    

    【讨论】:

    【解决方案2】:
    bool _visibility = false;
    ---------------------------
    Timer _timer;
    int _start = 1;
    
     --------------------------
      void startTimer() {
    const oneSec = const Duration(seconds: 1);
    _timer = new Timer.periodic(
        oneSec,
        (Timer timer) => setState(() {
              if (_start == 10) {
                timer.cancel();
                _changed(true);
              } else {
                _start = _start + 1;
              }
            }));
      }
     ---------------------------------
      void _changed(bool visibility) {
    setState(()
      if (_start == 10) {
        _visibility = visibility;
      }
      });
      }
     ---------------------------
      @override
      void initState() {
      super.initState();
      startTimer();
      setState(() {});
      }
    -----------------------------
     _visibility ? new Row(
      // create Widget
    
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-21
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 2017-08-29
      • 2020-01-28
      相关资源
      最近更新 更多