如何在特定时间段内显示小部件?

时间:2019-04-25 09:36:02

标签: timer flutter

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

2 个答案:

答案 0 :(得分: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
  });
});

答案 1 :(得分:1)

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

  )