Search code examples
timerflutter

How to show a widget for some particular amount of time?


I use an icon on my home screen to show user that some process is going on. I want this icon to be visible for some particular time (say 100sec). User might navigate to various screens but when he comes back to home screen, he should be able to see the icon and the icon should disappear after 100 sec. How do I do this?


Solution

  • 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,
        );
      }
    }
    

    refer to this link How to run code after some delay in Flutter?

    Alternatively you can use below code to implement the delayed state update:

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