使用Flutter动画使小部件的高度变化

3
我希望能够为该小部件添加高度动画效果,但不需要两个手(:
我尝试更改材料小部件的高度,但没有任何变化。 enter image description here
1个回答

15

要为高度添加动画,您需要使用 AnimationController 自己处理动画。下面是一个完整的示例:

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: AnimatedElevationButton(),
        ),
      ),
    );
  }
}

class AnimatedElevationButton extends StatefulWidget {
  @override
  _AnimatedElevationButtonState createState() =>
      _AnimatedElevationButtonState();
}

class _AnimatedElevationButtonState extends State<AnimatedElevationButton>
    with SingleTickerProviderStateMixin {
  AnimationController _animationController;
  Animation<double> _animationTween;

  @override
  void initState() {
    super.initState();

    _animationController = AnimationController(
      duration: Duration(milliseconds: 30),
      vsync: this,
    );
    _animationTween =
        Tween(begin: 20.0, end: 0.0).animate(_animationController);
    _animationController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: _onTapDown,
      onTapUp: _onTapUp,
      child: Material(
        color: Colors.red,
        borderRadius: BorderRadius.circular(8.0),
        elevation: _animationTween.value,
        child: SizedBox(
          width: 100,
          height: 50,
        ),
      ),
    );
  }

  void _onTapDown(TapDownDetails details) {
    _animationController.forward();
  }

  void _onTapUp(TapUpDetails details) {
    _animationController.reverse();
  }
}

1
不要忘记释放_animationController。 - Gpack

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