Search code examples
timerdartflutter

Flutter - Blinking button


I need a call the user attention to a button. The first idea that came to mind is to add a blink animation. I really don't know how to do that, but I tried to make it work with the following code:

Timer timer = new Timer(new Duration(seconds: 1), () {
  //basic logic to change the color variable here
  setState(() {});
});

It is straightforward, every second setState is called and the widget is created again.

But it doesn't work, the timer is called only once. And, besides that, calling setState within a Timer seems wrong to me.

There is a better approach to this?


Solution

  • You can achieve this in an easy way using AnimationController and FadeTransition widget, here you have the code:

      class MyBlinkingButton extends StatefulWidget {
        @override
        _MyBlinkingButtonState createState() => _MyBlinkingButtonState();
      }
    
      class _MyBlinkingButtonState extends State<MyBlinkingButton>
          with SingleTickerProviderStateMixin {
        AnimationController _animationController;
    
        @override
        void initState() {
          _animationController =
              new AnimationController(vsync: this, duration: Duration(seconds: 1));
          _animationController.repeat(reverse: true);
          super.initState();
        }
    
        @override
        Widget build(BuildContext context) {
          return FadeTransition(
            opacity: _animationController,
            child: MaterialButton(
              onPressed: () => null,
              child: Text("Text button"),
              color: Colors.green,
            ),
          );
        }
    
        @override
        void dispose() {
          _animationController.dispose();
          super.dispose();
        }
      }
    

    Usage:

    main() {
      runApp(
        MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Material(
            child: Center(
              child: MyBlinkingButton(),
            ),
          ),
        ),
      );
    }
    

    DartPad example

    Result:

    enter image description here