30

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?

1
  • Depending on your needs you may want to apply a Curve to Diego's answer Commented Aug 7, 2018 at 20:02

4 Answers 4

54

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

6
  • 1
    This is great! Thank you very much Diego.
    – Notheros
    Commented Aug 7, 2018 at 19:15
  • 2
    Bad idea. Use AnimatedWidget or AnimatedBuilder instead of doing such setState call Commented Aug 7, 2018 at 19:46
  • This is perfect, but i'll mix it with the answer bellow for a more smooth result
    – Jose Jet
    Commented Oct 17, 2018 at 7:05
  • Use SingleTickerProviderStateMixin instead of TickerProviderStateMixin as it is slightly more efficient in the case of the class only ever needing one Ticker. Here a single AnimationController was created during the lifetime of the class. Commented Mar 30, 2019 at 5:41
  • 2
    Can get a better effect by using _animationController.repeat(reverse: true); Commented Sep 22, 2020 at 15:55
15

You can do that with this approach also. My logic is a little different I am using alternate for animation. Once animation completed in forward I'm coming backward.

Which is good for eyesight

ie:

forward -> backward

backward -> forward

and so on

import 'package:flutter/material.dart';
import 'package:flutter/animation.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Wordpress App',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new BlinkAnimation(),
    );
  }
}

class BlinkAnimation extends StatefulWidget {
  @override
  _BlinkAnimationState createState() => _BlinkAnimationState();
}

class _BlinkAnimationState extends State<BlinkAnimation>
    with SingleTickerProviderStateMixin {
  Animation<Color> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = AnimationController(
        duration: const Duration(milliseconds: 500), vsync: this);
    final CurvedAnimation curve =
        CurvedAnimation(parent: controller, curve: Curves.linear);
    animation =
        ColorTween(begin: Colors.white, end: Colors.blue).animate(curve);
    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
      setState(() {});
    });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text('Blink Animation'),
      ),
      body: new Center(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) {
            return new Container(
              child: new RaisedButton(
                color: animation.value,
                onPressed: () {
                  controller.forward();
                },
                child: Text('Blink Animation'),
              ),
            );
          },
        ),
      ),
    );
  }

  dispose() {
    controller.dispose();
    super.dispose();
  }
}
4
  • Your logic works great too. Thank you for you answer.
    – Notheros
    Commented Aug 7, 2018 at 19:35
  • Works good, I think it looks better with Curves.easeInOut instead of Curves.linear but maybe that's just a personal preference
    – MobileMon
    Commented Apr 12, 2020 at 17:57
  • 2
    Please add a gif to your answer. Answers which are related to design issues should consist gifs and screenshots. Commented Feb 11, 2021 at 11:01
  • @genericUser I just posted an answer with code from this answer updated to latest version, and with a gif demo :)
    – Aleksandar
    Commented Feb 2, 2022 at 21:25
5

Here is the example from the answer by @nitishk72 but with code updated to null safety and more recent Flutter version.

Result:

Flutter blinking text code example

Code:

You can just copy this to DartPad.dev and it will work :)

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Blink animation demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: BlinkAnimation(),
    );
  }
}

class BlinkAnimation extends StatefulWidget {
  @override
  _BlinkAnimationState createState() => _BlinkAnimationState();
}

class _BlinkAnimationState extends State<BlinkAnimation>
    with SingleTickerProviderStateMixin {
  late Animation<Color?> animation;
  late AnimationController controller;

  @override
  initState() {
    super.initState();
    controller = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    );
    final CurvedAnimation curve =
        CurvedAnimation(parent: controller, curve: Curves.linear);
    animation =
        ColorTween(begin: Colors.white, end: Colors.blue).animate(curve);
    // Keep the animation going forever once it is started
    animation.addStatusListener((status) {
      // Reverse the animation after it has been completed
      if (status == AnimationStatus.completed) {
        controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
      setState(() {});
    });
    // Remove this line if you want to start the animation later
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Blink Animation'),
      ),
      body: Center(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget? child) {
            return Container(
              color: animation.value,
              padding: const EdgeInsets.all(8.0),
              child: InkWell(
                onTap: () {
                  // Start the animation or do something else on click
                  // controller.forward();
                  print('button does something!');
                },
                child: const Text('Blink Animation'),
              ),
            );
          },
        ),
      ),
    );
  }

  @override
  dispose() {
    controller.dispose();
    super.dispose();
  }
}
3

Current answers are great but do not cover opacity blink (repeated fade in, fade out), you may use the following widget if that's your goal:

class BlinkAnimation extends StatefulWidget {
  final Widget child;

  const BlinkAnimation({
    Key? key,
    required this.child,
  }) : super(key: key);

  @override
  State<BlinkAnimation> createState() => _BlinkAnimationState();
}

class _BlinkAnimationState extends State<BlinkAnimation>
    with SingleTickerProviderStateMixin {
  late final AnimationController controller = AnimationController(
    duration: const Duration(seconds: 2),
    vsync: this,
  )..repeat(reverse: true);
  late final Animation<double> animation = CurvedAnimation(
    parent: controller,
    curve: Curves.easeIn,
  );

  @override
  Widget build(BuildContext context) {
    return FadeTransition(opacity: animation, child: widget.child);
  }

  @override
  dispose() {
    controller.dispose();
    super.dispose();
  }
}

based on FadeTransition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.