在 Flutter 中如何用动画将容器从 0 高度扩展到其内容物的高度?

mwa*_*ior 10 flutter flutter-animation flutter-container

我有一个从零高度开始的容器,需要在用户交互后扩展。

  • 我尝试使用 AnimatedContainer / AnimatedSize 并将子窗口小部件的高度从 更改为0null但在这两种情况下,Flutter 抱怨它无法从 插入0null
  • 我还尝试使用 BoxConstraints (使用扩展maxHeight = double.infinity)而不是显式高度,在这种情况下,Flutter 抱怨它无法从有限值插值到不定值。
  • 我还尝试将 mainAxisSize 设置为 min/max,在这种情况下 Flutter 会vsync抱怨null.

如何以动画方式扩展小部件,使其动态增长到足以包裹其内容?如果这不能动态完成,那么有什么安全的方法来调整内容的大小,以便它们在不同的屏幕尺寸上都有意义?在 Web 开发中,我知道类似的事情em是相对大小的,但在 Flutter 的上下文中,我不知道如何可靠地控制事物的大小。


更新:正如 @pskink 所建议的,将子项包装在 Align 小部件中并为 Align 的 heightFactor 参数设置动画可实现折叠。然而,当崩溃的孩子本身有孩子时,我仍然很难让崩溃工作。例如,Column 小部件根本不会使用 ClipRect 进行剪辑(请参阅https://github.com/flutter/flutter/issues/29357),即使我使用 Wrap 而不是 Column,如果 Wrap 的孩子们是行。不知道如何让剪辑始终如一地工作。

koh*_*kob 30

也许你也可以用SizeTransition解决这个问题?

在此输入图像描述

class VariableSizeContainerExample extends StatefulWidget {
  VariableSizeContainerExample();

  @override
  _VariableSizeContainerExampleState createState() => _VariableSizeContainerExampleState();
}

class _VariableSizeContainerExampleState extends State<VariableSizeContainerExample> with TickerProviderStateMixin {
  AnimationController _controller;
  Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 1),
      vsync: this,
    );
    _animation = CurvedAnimation(
      parent: _controller,
      curve: Curves.fastLinearToSlowEaseIn,
    );
  }

  _toggleContainer() {
    print(_animation.status);
    if (_animation.status != AnimationStatus.completed) {
      _controller.forward();
    } else {
      _controller.animateBack(0, duration: Duration(seconds: 1));
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Column(
            children: [
              TextButton(
                onPressed: () => _toggleContainer(),
                child: Text("Toggle container visibility"),
              ),
              SizeTransition(
                sizeFactor: _animation,
                axis: Axis.vertical,
                child: Container(
                  child: Text(
                    "This can have variable size",
                    style: TextStyle(fontSize: 40),
                  ),
                ),
              ),
              Text("This is below the above container"),
            ],
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)