Flutter動畫--->了解篇


1. 一個簡單例子

我們通過一個下面一個簡單的放大動畫來了解動畫中相關(guān)的Api。

import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';

class HomeApp extends StatefulWidget {
  _HomeAppState createState() => new _HomeAppState();
}

class _HomeAppState extends State<HomeApp> with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = new AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    animation = new Tween(begin: 20.0, end: 300.0).animate(controller)
      ..addListener(() {
        setState(() {
          // the state that has changed here is the animation object’s value
        });
      });
  }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('一個簡單的放大動畫'),
        ),
        body: new Center(
          child: Column(
            children: <Widget>[
              new Container(
                margin: new EdgeInsets.symmetric(vertical: 10.0),
                height: animation.value,
                width: animation.value,
                child: new FlutterLogo(),
              ),
              FlatButton(
                onPressed: () {
                  controller.forward();
                },
                child: Text('放大'),
              )
            ],
          ),
        ),
      ),
    );
  }

  dispose() {
    controller.dispose();
    super.dispose();
  }
}

void main() {
  runApp(new HomeApp());
}

從上述代碼中,我們知道要實現(xiàn)一個簡單的縮放動畫,我們需要了解下面的api,

  • Animation
    該對象是Flutter動畫庫中的一個核心類,擁有當(dāng)前動畫的當(dāng)前狀態(tài)(例如它是開始、停止還是向前或向后移動)以及通過value獲取動畫的當(dāng)前值,但該對象本身和UI渲染沒有任何關(guān)系,Animation可以生成除double之外的其他類型值,如:Animation<Color>或Animation<Size>。
  • AnimationController
    主要是用來管理Animation的。該類派生自Animation<double>。默認情況下,AnimationController在給定的時間段內(nèi)會線性的生成0.0到1.0之間的數(shù)字。當(dāng)創(chuàng)建一個AnimationController時,需要傳遞一個vsync參數(shù),存在vsync時會使得當(dāng)動畫的UI不在當(dāng)前屏幕時,消耗不必要的資源。
  • Tween
    默認情況下,AnimationController對象的范圍從0.0到1.0,如果我們需要不同的數(shù)據(jù)類型,則可以使用Tween來配置動畫以生成不同的范圍活數(shù)據(jù)類型的值。
  • addListener
    是動畫的監(jiān)聽器,只要動畫的值發(fā)生變化就會調(diào)用監(jiān)聽器,因此我們可以常用監(jiān)聽器來更新我們的UI界面。

2. AnimatedWidget

上述例子中,我們最終是在addListener中利用setState方法來給widget添加動畫,而AnimatedWidget的相關(guān)系列將會幫我們省略掉這一步,F(xiàn)lutter API提供的關(guān)于AnimatedWidget的示例包括:AnimatedBuilder、AnimatedModalBarrier、DecoratedBoxTransition、FadeTransition、PositionedTransition、RelativePositionedTransition、RotationTransition、ScaleTransition、SizeTransition、SlideTransition。

import 'package:flutter/material.dart';

class AnimatedLogo extends AnimatedWidget {
  AnimatedLogo({Key key, Animation<double> animation})
      : super(key: key, listenable: animation);
  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    return new Center(
      child: new Container(
        margin: new EdgeInsets.symmetric(vertical: 10.0),
        height: animation.value,
        width: animation.value,
        child: new FlutterLogo(),
      ),
    );
  }
}
class HomeApp extends StatefulWidget {
  _HomeAppState createState() => new _HomeAppState();
}

class _HomeAppState extends State<HomeApp> with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = new AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    animation = new Tween(begin: 20.0, end: 300.0).animate(controller)
      ..addListener(() {
        setState(() {
          // the state that has changed here is the animation object’s value
        });
      });
  }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('一個簡單的放大動畫'),
        ),
        body: new Center(
          child: Column(
            children: <Widget>[
              AnimatedLogo(animation: animation),
              FlatButton(
                onPressed: () {
                  controller.forward();
                },
                child: Text('放大'),
              )
            ],
          ),
        ),
      ),
    );
  }

  dispose() {
    controller.dispose();
    super.dispose();
  }
}

void main() {
  runApp(new HomeApp());
}

3. 監(jiān)聽動畫的狀態(tài)

addStatusListener方法可以監(jiān)聽到動畫在整個運動期間的狀態(tài)。

class _HomeAppState extends State<HomeApp> with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = new AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    animation = new Tween(begin: 20.0, end: 300.0).animate(controller)
      ..addStatusListener((state){
        print('----->$state');
      });
  }

打印log:

flutter: ----->AnimationStatus.forward
flutter: ----->AnimationStatus.completed

下面我們利用該監(jiān)聽來實現(xiàn)一個循環(huán)動畫,

class _HomeAppState extends State<HomeApp> with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = new AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    animation = new Tween(begin: 20.0, end: 300.0).animate(controller)
      ..addStatusListener((state) {
        print('----->$state');
        if (state == AnimationStatus.completed) {
          controller.reverse();
        } else if (state == AnimationStatus.dismissed) controller.forward();
      });
  }

4. 利用AnimatedBuilder進行重構(gòu)

上面的例子中我們發(fā)現(xiàn)一個問題:動畫的logo我們不可以任意的替換。這時我們就可以利用AnimatedWidget來實現(xiàn)。

class GrowTransition extends StatelessWidget {
  GrowTransition({this.child, this.animation});

  final Widget child;
  final Animation<double> animation;

  Widget build(BuildContext context) {
    return new Center(
      child: new AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) {
            return new Container(
                height: animation.value, width: animation.value, child: child);
          },
          child: child),
    );
  }
}
class HomeApp extends StatefulWidget {
  _HomeAppState createState() => new _HomeAppState();
}

class _HomeAppState extends State<HomeApp> with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = new AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    final CurvedAnimation curved =
        new CurvedAnimation(parent: controller, curve: Curves.easeIn);
    animation = new Tween(begin: 20.0, end: 300.0).animate(curved);
  }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('一個簡單的放大動畫'),
        ),
        body: new Center(
          child: Column(
            children: <Widget>[
              GrowTransition(
                child: FlutterLogo(),
                animation: animation,
              ),
              FlatButton(
                onPressed: () {
                  controller.forward();
                },
                child: Text('放大'),
              )
            ],
          ),
        ),
      ),
    );
  }

  dispose() {
    controller.dispose();
    super.dispose();
  }
}

void main() {
  runApp(new HomeApp());
}

重構(gòu)之后,我們發(fā)現(xiàn),我們可以將logo替換成任何我們想要的一個widget。

5. 并行動畫

在上面動畫的基礎(chǔ)上我們再給logo添加一個透明度變化的動畫。下面的例子中我們將學(xué)會如何在同一個動畫控制器上使用多個Tween,其中每個Tween管理動畫中的不同效果。

class AnimatedLogo extends AnimatedWidget {
  AnimatedLogo({Key key, Animation<double> animation})
      : super(key: key, listenable: animation);
  static final _opacityTween = new Tween(begin: 0.1, end: 1.0);
  static final _sizeTween = new Tween(begin: 0.0, end: 300);

  @override
  Widget build(BuildContext context) {
    final Animation<double> animation = listenable;
    return new Center(
      child: new Opacity(
        opacity: _opacityTween.evaluate(animation),
        child: new Container(
          margin: new EdgeInsets.symmetric(vertical: 10.0),
          height: _sizeTween.evaluate(animation),
          width: _sizeTween.evaluate(animation),
          child: new FlutterLogo(),
        ),
      ),
    );
  }
}
class HomeApp extends StatefulWidget {
  _HomeAppState createState() => new _HomeAppState();
}

class _HomeAppState extends State<HomeApp> with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = new AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    animation = new CurvedAnimation(parent: controller, curve: Curves.easeIn);

    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
    });
  }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('一個簡單的放大動畫'),
        ),
        body: new Center(
          child: Column(
            children: <Widget>[
              AnimatedLogo(
                animation: animation,
              ),
              FlatButton(
                onPressed: () {
                  controller.forward();
                },
                child: Text('放大'),
              )
            ],
          ),
        ),
      ),
    );
  }

  dispose() {
    controller.dispose();
    super.dispose();
  }
}

void main() {
  runApp(new HomeApp());
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 如果我們想要一些東西動畫,我們必須改變大小或改變連續(xù)幀中對象的位置。例如,在第1幀中,我們的對象位于位置x,在第2...
    開心人開發(fā)世界閱讀 2,298評論 0 8
  • Flutter動畫類型 動畫分為兩類:基于tween或基于物理的。以下部分解釋了這些術(shù)語的含義,并指出您可以在其中...
    蓋世英雄_ix4n04閱讀 6,341評論 0 2
  • 參考來源:https://flutterchina.club/animations/ 動畫類型 補間(Tween)...
    _白羊閱讀 18,303評論 2 11
  • 1 那年,高曉松的一句話“生活不止眼前的茍且,還有詩和遠方的田野”,傳唱大江南北,讓多少年輕人熱血沸騰,蠢蠢欲動。...
    金新寶貝閱讀 1,507評論 8 3
  • 動筆之前,把自己以前的QQ說說翻了個遍,試圖找到一點靈感或是一個切入口來開始這里的開始,結(jié)果發(fā)現(xiàn)都是青春時代的稚嫩...
    滄海一霸閱讀 119評論 1 1

友情鏈接更多精彩內(nèi)容