首页 > 解决方案 > Flutter 将动画从小到大

问题描述

需要知道如何在启动画面上添加一些动画。我只需要在应用打开时添加中心图像会从小到大显示。

我的代码

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    super.initState();
    Timer(
        Duration(seconds: 3),
            () => Navigator.of(context).pushReplacement(MaterialPageRoute(
            builder: (BuildContext context) => HomeScreen())));
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/bg@3x.png"),
            fit: BoxFit.cover,
          ),
        ),
        child: Center(
          child: Image.asset("assets/logo@2x.png"),
        ) /* add child content here */,
      ),
    );
  }
}

标签: flutter

解决方案


为此,您可以使用Tween AnimationControllerwith to。AnimatedBuilder这是一个您只需要替换Container为您的示例,Image或者您也可以使用容器包装图像。

因为,您希望image增加初始屏幕的大小,所以使用in 的forward()属性。AnimationControllerinitState

然后将图像的heightandwidth属性替换为_animationSize.value. 在此处根据您的需要调整大小:

尺寸:

_tweenSize = Tween(begin: 50, end: 200);

期间:

_animationController = AnimationController(vsync: this, duration: Duration(milliseconds: 400));

代替:

 AnimatedBuilder(
            animation: _animationSize,
            builder: (context, child) {
              // Put your image here and replace height, width of image with _animationSize.value
              return Container(
                color: Colors.red,
                height: _animationSize.value,
                width: _animationSize.value,
              );
            }),
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with SingleTickerProviderStateMixin {
  Tween<double> _tweenSize;
  Animation<double> _animationSize;
  AnimationController _animationController;

  @override
  void initState() {
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 400));
    _tweenSize = Tween(begin: 50, end: 200);
    _animationSize = _tweenSize.animate(_animationController);
    _animationController.forward();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: AnimatedBuilder(
            animation: _animationSize,
            builder: (context, child) {
              // Put your image here and replace height, width of image with _animationSize.value
              return Container(
                color: Colors.red,
                height: _animationSize.value,
                width: _animationSize.value,
              );
            }),
      ),
    );
  }
}


推荐阅读