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

下面是我正在做的一段代码片段:

CustomAppBar类: 导入‘包装: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),

但我最终得到了这样一个动画:

enter image description here

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

更新:我try 将CustomAppBar添加到‘Body’中,而不是‘appbar’中,它工作起来很奇怪,但我很想知道是什么导致了这个问题.

推荐答案

我发现是preferredSizeGetter覆盖导致了这个问题.我相信这是因为当发生反向动画时,它从从preferredSize高度开始的高度开始,这使得它看起来像是在动画真正将你带到目标高度之前跳到那个位置.值preferredSize不是动画,这就是为什么您发现它大约从120开始,因为它的变化不受任何持续时间的限制.

好消息是,您可以将preferredSize设置为应用程序栏的最大高度,因为应用程序栏无论如何都是受限制的.在PreferredSizeWidget的文件中,它说:

一个小部件的界面,可以返回此小部件希望的大小为if it were otherwise unconstrained.

你的应用程序栏受其自身大小的限制,主要在AnimatedContainer个应用程序栏的height个,所以不必担心.您只需将其设置为固定值:

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

它将解决动画问题.

enter image description here

Flutter相关问答推荐

如何增加容器高度?

当第二页在单独的小工具中使用Navigator.pop时,Navigator.push不起作用

ShaderMask上的文本渐变问题

为什么我需要等待重新访问Firestore数据库,即使它已经做了之前?

底部导航栏项目在抖动中不更改 colored颜色

自定义ItemBuilderFlutter

Flutter 图标记移动

如何在Flutter 中共享选定文本

在Flutter 中更改扩展瓷砖的高度

Flutter 块消费者仅对特定的状态属性更改做出react

Riverpod 2.0-如何使用FutureOr和AutoDisposeSyncNotificationer处理api状态代码?

如何使用providerContainer监听/写入FutureProvider?

如何计算 Firestore 集合中的文档数量?

Flutter url_launcher 插件抛出java.lang.IllegalArgumentException:接收器未注册:io.flutter.plugins.urllauncher.WebViewActivity

Flutter 判断 Uint8List 是否有效 Image

当我使用 Confetti Widget 时,Flutter Android 和 IOS 应用程序崩溃

Flutter ListView 在 Column 中工作但在 Row 中不工作

具有 BLOC 和存储库模式的 Flutter Workmanager

Flutter snapShot.hasData 为假但响应有数据

有任何方法可以在应用程序移动背景恢复时显示 appopenAd