使用弹性动画折叠和展开Flutter小部件

5
在这个简单的UI中,我在屏幕右侧有一个容器,并希望使用弹性动画来折叠和展开它,例如在展开时使用elasticIn动画,在折叠时使用elasticOut动画。请保留HTML标签。

enter image description here

1个回答

6

您需要的是这个吗?

这里输入图片描述

import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
import 'dart:math';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Spring Box",
      theme: ThemeData(),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  Animation animationIn, animationOut;

  AnimationController _animationController;

  @override
  void initState() {
    _animationController = AnimationController(
      vsync: this,
      value: 1.0,
      duration: Duration(milliseconds: 500),
    );
    animationIn = CurvedAnimation(parent: _animationController, curve: Curves.elasticIn);
    animationOut = CurvedAnimation(parent: _animationController, curve: Curves.elasticIn);
  }

  _toggleExpanded() {
    if (_animationController.status == AnimationStatus.completed) {
      _animationController.reverse();
    } else {
      _animationController.forward();
    }
  }

  @override
  Widget build(BuildContext context) {
    var isExpanded = _animationController.status != AnimationStatus.completed;
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: _toggleExpanded,
        child: Icon(Icons.add),
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          CollapsAnimation(
            animation: isExpanded ? animationOut : animationIn,
            child: Container(
              color: Color(0xFF404bc4),
            ),
          ),
        ],
      ),
      backgroundColor: Color(0xFFe8e8e8),
    );
  }
}

class CollapsAnimation extends AnimatedWidget {
  CollapsAnimation({key, animation, this.child})
      : super(
          key: key,
          listenable: animation,
        );

  final Widget child;
  final Tween tween = Tween<double>(begin: 0, end: 80);

  @override
  Widget build(BuildContext context) {
    Animation<double> animation = listenable;

    var animationValue = tween.evaluate(animation);
    double width = animationValue >= 0.0 ? animationValue : 0.0;
    return Container(
      width: width,
      child: child,
    );
  }
}

我想要的有一点不同,就是当容器折叠时使用 elasticOut,这意味着三个动画,第三个动画是当 container 折叠时。 - DolDurma
嗯,像那样? - Kherel
@Kherek非常感谢,我接受了您的答案。您的所有回答都是正确的,但有一点不同,如果您有空闲时间,有三个动画:第一个是在没有任何动画的情况下开始扩展,第二个是当容器扩展时,第三个动画是当容器折叠时,我该如何获取您之前回答的帖子? - DolDurma
2
谢谢,这是第一个版本:https://gist.github.com/kherel/1048888bf4da291b4d79596c2828d131 - Kherel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接