简体   繁体   中英

How to custom fadeIn/fadeOut animation for SnackBar in flutter?

I want to custom show/hide SnackBar in Flutter with animation fadeIn/fadeOut

and time of fadeIn/fadeOut animation about 300 milliseconds

    final SnackBar snackBar = SnackBar(
        backgroundColor: Colors.transparent,
        behavior: SnackBarBehavior.floating,
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
        margin: const EdgeInsets.only(bottom: 20.0),
        elevation: 0,
        duration: const Duration(seconds: 3),
        animation: , //<- TODO: Animation for SnackBar
        content: Container(
            width: 200,
            height: 60,
            color: Colors.red,
            child: const Text('Custom fadeIn/fadeOut animation',
                style: TextStyle(color: Colors.white))));

    scaffoldMessengerKey.currentState?.showSnackBar(snackBar);

How to custom animation for SnackBar ?

You can use controller and animation to achieve custom snackbar.

class _MyWidgetState extends State<MyWidget>
    with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController controller;
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const Duration(seconds: 0),
      vsync: this,
    );
    animation = CurvedAnimation(parent: controller, curve: Curves.easeInOut)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          controller.reverse();
        }
      });
  }

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

And add the animation in the animation prop of Snackbar , You can even add fadeTransition for the content to fade in and out.

ElevatedButton(
  onPressed: () {
    controller.forward();
    SnackBar(
      animation: animation,
      behavior: SnackBarBehavior.floating,
      margin: const EdgeInsets.all(16),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10)),
      content: FadeTransition(  // 👈 You can even add FadeTransition to the content
                opacity: controller, child: const Text("Content")),
                duration: const Duration(seconds: 3));
              },
     child: const Text(" Custom Snackbar ")),
   }
);

In addition to this you can also use another_flushbar

Also refer How to implement floating Snackbar animation in flutter?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM