Flutter AppBar 动画反向 bug

问题描述 投票:0回答:1

所以,我正在使用 Flutter 构建一个应用程序,在主页中,我想要一个更大的 AppBar,而在其他页面中,AppBar 恢复到常规大小,我设法以良好且流畅的动画实现前者,但是我无法让后者工作。

这是我正在做的事情的代码片段:

自定义应用栏类: 导入'包:flutter/material.dart';

class CustomAppBar extends StatefulWidget implements PreferredSizeWidget{
  double height;
  String title;
  Color color;
  Color textColor;

  CustomAppBar(this.height, this.title, this.color, this.textColor, {super.key});

  @override
  State<CustomAppBar> createState() => _CustomAppBarState();

  @override
  // TODO: implement preferredSize
  Size get preferredSize => Size.fromHeight(height);
}

class _CustomAppBarState extends State<CustomAppBar> {
  @override
  Widget build(BuildContext context) {
    return PreferredSize(
      preferredSize: Size.fromHeight(widget.height),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 500),
        curve: Curves.decelerate,
        height: widget.height,
        child: Container(
          color: Colors.green,
        ),

      ),
    );
  }
}

然后在 Scaffold 中,我像这样分配 AppBar:

appBar: CustomAppBar(height, getTitle(currentIndex), Colors.purple, Colors.white),

但是我最终得到了这样的动画:

请注意,当单击第二个导航项时,它如何从高度 260 跳到大约 120,然后从 120 动画到 90(数字为近似值)

更新:我尝试将 CustomAppBar 添加到“body”而不是“appbar”,但效果很奇怪,但我很想知道是什么原因导致了问题。

flutter flutter-animation appbar flutter-appbar
1个回答
0
投票

我发现

preferredSize
getter 重写导致了这个问题。我相信会发生这种情况,因为当反向动画发生时,它从从
preferredSize
高度获取的高度开始,这使得它看起来像是在动画实际将您带到目标高度之前跳到该位置。
preferredSize
的值不是动画的,这就是为什么你发现它大约从120开始,因为它的变化不受任何持续时间的限制。

好处是,您可以将

preferredSize
设置为应用程序栏的最大高度,因为应用程序栏无论如何都是受到限制的。在 PreferredSizeWidget 的文档中,它说:

小部件的接口,可以返回该小部件喜欢的尺寸如果它不受其他约束

您的应用栏受到自身大小的限制,主要集中在

height
AnimatedContainer
中,所以无需担心。您可以将其设置为固定值:

@override
Size get preferredSize => Size.fromHeight(260);

它将解决动画问题。

© www.soinside.com 2019 - 2024. All rights reserved.