Flutter AnimatedSwitcher 在 child 之间跳跃 - 已解决 -

标签 flutter dart flutter-animation

亲爱的 Flutter 社区!

我正在尝试在扩展面板列表中实现一些自定义设计。因此,我想创建某种动画,从一个 View (例如标题)平滑地动画到另一个具有其他维度的 View (例如磁贴的完整信息)(显然,完整信息将高于标题)。使用 AnimatedContainer 很容易实现这一点。但是,我需要标题小部件和完整信息小部件的高度才能在这两个高度之间设置动画。由于这些值在瓦片(其他信息 -> 可能是其他高度)之间不同,并且通过全局键跟踪高度不是我的首选解决方案,我决定使用更简单的 AnimatedSwitcher 代替。但是,我的 AnimatedSwitcher 的行为很奇怪。首先,ListView 中的其他图块(在我的示例中为按钮)立即向下移动,随后图块展开。有没有人知道我如何实现一些代码以实现与 AnimatedContainer 相同的动画(按钮/其他图块与图块展开同时向下移动)?提前感谢您的任何建议。这是我的代码:

class MyPage extends State {
List _items;
int pos;

@override
void initState() {
pos = 0;
_items = [
  Container(
    color: Colors.white,
    width: 30,
    key: UniqueKey(),
    child: Column(
      children: <Widget>[Text('1'), Text('2')], //example that should visualise different heights
    ),
  ),
  Container(
    width: 30,
    color: Colors.white,
    key: UniqueKey(),
    child: Column(
      children: <Widget>[Text('1'), Text('2'), Text('44534'), Text('534534')],
    ),
  )
];
super.initState();
}

@override
Widget build(BuildContext context) {

return Scaffold(
  body: ListView(
    padding: EdgeInsets.only(top: 100),
    children: <Widget>[
      AnimatedSwitcher(
        duration: Duration(seconds: 1),
        transitionBuilder: (child, animation) => ScaleTransition(
          child: child,
          scale: animation,
        ),
        child: _items[pos],
      ),
      RaisedButton(
          child: Text('change'),
          onPressed: pos == 0
              ? () {
                  setState(() => pos = 1);
                }
              : () {
                  setState(() => pos = 0);
                })
    ],
  ),
);
}
}

解决方法很简单。刚刚发现存在一个 AnimatedSize Widget 可以自动找出其子项的大小。

最佳答案

我偶然发现了这篇文章,因为我遇到了类似的问题,所以我决定创建一个 tutorial here关于如何混合AnimatedSwitcherAnimatedSize来解决这个问题。动画不会同时发生,但优点是您可以完全控制提供给切换器的动画。
我最终这样做了(请注意,我使用的是 BlocBuilderAnimatedSizeWidgetAnimatedSize 的基本实现:

    AnimatedSizeWidget(
              duration: const Duration(milliseconds: 250),
              child: BlocBuilder<SwapCubit, bool>(
                builder: (context, state) {
                  return AnimatedSwitcher(
                    duration: const Duration(milliseconds: 1000),
                    child: state
                        ? Icon(Icons.face, size: 80, key: Key("80"))
                        : Icon(Icons.face, size: 160, key: Key("160")),
                  );
                },
              ),
            ),

关于Flutter AnimatedSwitcher 在 child 之间跳跃 - 已解决 -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61431105/

相关文章:

dart - js-interop:从dart传递javascript对象

flutter - 如何在 flutter 中使用 LinearGradient 和变换?

flutter - 如何在 flutter 中动态隐藏和显示底栏

flutter - 在 GridView 中更改单个小部件的属性

flutter - 我将InkWell小部件连续放置,但无法正常工作

Dart 命名约定

animation - 在 Flutter 动画中更新动画值的正确方法是什么?

postgresql - flutter 和 PostgreSQL

Flutter图像装饰错位

dart - Navigator routes 清除flutter的堆栈