簡體   English   中英

如何在flutter中為SnackBar自定義fadeIn/fadeOut animation?

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

我想在 Flutter 中使用 animation fadeIn/fadeOut自定義show/hide SnackBar

fadeIn/fadeOut的時間 animation 大約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);

如何為SnackBar自定義 animation ?

可以使用controlleranimation來實現自定義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();
  }

並在Snackbaranimation屬性中添加animation ,甚至可以添加fadeTransition讓內容淡入淡出。

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

除此之外,您還可以使用another_flushbar

另請參閱How to implement floating Snackbar animation in flutter?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM