如何在颤动中为折叠元素设置动画

how to animate collapse elements in flutter

当用户点击带有动画的不同小部件(同级或父级)时,如何展开和折叠小部件?

new Column(
    children: <Widget>[
        new header.IngridientHeader(
            new Icon(
                Icons.fiber_manual_record,
                color: AppColors.primaryColor
            ),
            'Voice Track 1'
        ),
        new Grid()
    ],
)

我希望用户能够点击 header.IngridientHeader,然后 Grid 小部件应该切换(如果可见则隐藏,其他方式关闭)

编辑:

我正在尝试做一些在 bootstrap 中称为崩溃的事情。 getbootstrap.com/docs/4.0/components/collapse

编辑2: header.IngridientHeader应该一直呆在原地 Grid() 是可滚动(水平)小部件。

我认为您正在寻找 ExpansionTile 小部件。这需要一个 title 属性 相当于 header 和 children 属性 ,您可以将要在切换时显示或隐藏的小部件传递给它。 您可以找到如何使用它的示例 here

简单示例用法:

new ExpansionTile(title: new Text("Numbers"),
      children: <Widget>[
        new Text("Number: 1"),
        new Text("Number: 2"),
        new Text("Number: 3"),
        new Text("Number: 4"),
        new Text("Number: 5")
      ],
),

希望对您有所帮助!

或者您可以只使用 AnimatedContainer 来模仿这种行为。

class AnimateContentExample extends StatefulWidget {
  @override
  _AnimateContentExampleState createState() => new _AnimateContentExampleState();
}

class _AnimateContentExampleState extends State<AnimateContentExample> {
  double _animatedHeight = 100.0;
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: new Text("Animate Content"),),
      body: new Column(
        children: <Widget>[
          new Card(
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                new GestureDetector(
                  onTap: ()=>setState((){
                    _animatedHeight!=0.0?_animatedHeight=0.0:_animatedHeight=100.0;}),
                  child:  new Container(
                  child: new Text("CLICK ME"),
                  color: Colors.blueAccent,
                  height: 25.0,
                    width: 100.0,
                ),),
                new AnimatedContainer(duration: const Duration(milliseconds: 120),
                  child: new Text("Toggle Me"),
                  height: _animatedHeight,
                  color: Colors.tealAccent,
                  width: 100.0,
                )
              ],
            ) ,
          )
        ],
      ),
    );
  }
}

如果您想将小部件折叠为零高度或零宽度,并且 child 在折叠时会溢出,我建议 SizeTransition or ScaleTransition

这是一个 ScaleTransition 小部件的示例,用于折叠四个黑色按钮和状态文本的容器。我的 ExpandedSection 小部件与列一起使用以获得以下结构。

将动画与 SizeTransition 小部件一起使用的小部件示例:

class ExpandedSection extends StatefulWidget {

  final Widget child;
  final bool expand;
  ExpandedSection({this.expand = false, this.child});

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

class _ExpandedSectionState extends State<ExpandedSection> with SingleTickerProviderStateMixin {
  AnimationController expandController;
  Animation<double> animation; 

  @override
  void initState() {
    super.initState();
    prepareAnimations();
    _runExpandCheck();
  }

  ///Setting up the animation
  void prepareAnimations() {
    expandController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 500)
    );
    animation = CurvedAnimation(
      parent: expandController,
      curve: Curves.fastOutSlowIn,
    );
  }

  void _runExpandCheck() {
    if(widget.expand) {
      expandController.forward();
    }
    else {
      expandController.reverse();
    }
  }

  @override
  void didUpdateWidget(ExpandedSection oldWidget) {
    super.didUpdateWidget(oldWidget);
    _runExpandCheck();
  }

  @override
  void dispose() {
    expandController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizeTransition(
      axisAlignment: 1.0,
      sizeFactor: animation,
      child: widget.child
    );
  }
}

AnimatedContainer 也有效,但如果 child 不能调整为零宽度或零高度,Flutter 会抱怨溢出。

输出:


代码:

class FooPageState extends State<SoPage> {
  static const _duration = Duration(seconds: 1);
  int _flex1 = 1, _flex2 = 2, _flex3 = 1;

  @override
  Widget build(BuildContext context) {
    final total = _flex1 + _flex2 + _flex3;
    final height = MediaQuery.of(context).size.height;
    final height1 = (height * _flex1) / total;
    final height2 = (height * _flex2) / total;
    final height3 = (height * _flex3) / total;

    return Scaffold(
      body: Column(
        children: [
          AnimatedContainer(
            height: height1,
            duration: _duration,
            color: Colors.red,
          ),
          AnimatedContainer(
            height: height2,
            duration: _duration,
            color: Colors.green,
          ),
          AnimatedContainer(
            height: height3,
            duration: _duration,
            color: Colors.blue,
          ),
        ],
      ),
    );
  }
}

感谢@Adam Jonsson,他的回答解决了我的问题。这是关于如何使用ExpandedSection的演示,希望对您有所帮助。

class ExpandedSection extends StatefulWidget {
  final Widget child;
  final bool expand;

  ExpandedSection({this.expand = false, this.child});

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

class _ExpandedSectionState extends State<ExpandedSection>
    with SingleTickerProviderStateMixin {
  AnimationController expandController;
  Animation<double> animation;

  @override
  void initState() {
    super.initState();
    prepareAnimations();
    _runExpandCheck();
  }

  ///Setting up the animation
  void prepareAnimations() {
    expandController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 500));
    animation = CurvedAnimation(
      parent: expandController,
      curve: Curves.fastOutSlowIn,
    );
  }

  void _runExpandCheck() {
    if (widget.expand) {
      expandController.forward();
    } else {
      expandController.reverse();
    }
  }

  @override
  void didUpdateWidget(ExpandedSection oldWidget) {
    super.didUpdateWidget(oldWidget);
    _runExpandCheck();
  }

  @override
  void dispose() {
    expandController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizeTransition(
        axisAlignment: 1.0, sizeFactor: animation, child: widget.child);
  }
}
  
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Demo'),
        ),
        body: Home(),
      ),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool _expand = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Header(
          onTap: () {
            setState(() {
              _expand = !_expand;
            });
          },
        ),
        ExpandedSection(child: Content(), expand: _expand,)
      ],
    );
  }
}

class Header extends StatelessWidget {
  final VoidCallback onTap;

  Header({@required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        color: Colors.cyan,
        height: 100,
        width: double.infinity,
        child: Center(
          child: Text(
            'Header -- Tap me to expand!',
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        ),
      ),
    );
  }
}

class Content extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.lightGreen,
      height: 400,
    );
  }
}