Flutter折叠并使用弹性动画扩展小部件

时间:2019-08-29 12:00:18

标签: flutter flutter-animation

在下面这个简单的用户界面中,我拥有Container的屏幕右侧,我想用elastic动画进行折叠和展开,例如在展开elasticIn动画上进行折叠{{1 }}。

enter image description here

1 个答案:

答案 0 :(得分:2)

这是您需要的吗?

enter image description here

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,
    );
  }
}