【Flutter 實(shí)戰(zhàn)】動(dòng)畫序列、共享動(dòng)畫、路由動(dòng)畫

老孟導(dǎo)讀:此篇文章是 Flutter 動(dòng)畫系列文章第四篇,本文介紹動(dòng)畫序列、共享動(dòng)畫、路由動(dòng)畫。

動(dòng)畫序列

Flutter中組合動(dòng)畫使用Interval,Interval繼承自Curve,用法如下:

Animation _sizeAnimation = Tween(begin: 100.0, end: 300.0).animate(CurvedAnimation(
    parent: _animationController, curve: Interval(0.5, 1.0)));

表示_sizeAnimation動(dòng)畫從0.5(一半)開始到結(jié)束,如果動(dòng)畫時(shí)長(zhǎng)為6秒,_sizeAnimation則從第3秒開始。

Intervalbeginend參數(shù)值的范圍是0.0到1.0。

下面實(shí)現(xiàn)一個(gè)先執(zhí)行顏色變化,在執(zhí)行大小變化,代碼如下:

class AnimationDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _AnimationDemo();
}

class _AnimationDemo extends State<AnimationDemo>
    with SingleTickerProviderStateMixin {
  AnimationController _animationController;
  Animation _colorAnimation;
  Animation _sizeAnimation;

  @override
  void initState() {
    _animationController =
        AnimationController(duration: Duration(seconds: 5), vsync: this)
    ..addListener((){setState(() {
      
    });});

    _colorAnimation = ColorTween(begin: Colors.red, end: Colors.blue).animate(
        CurvedAnimation(
            parent: _animationController, curve: Interval(0.0, 0.5)));

    _sizeAnimation = Tween(begin: 100.0, end: 300.0).animate(CurvedAnimation(
        parent: _animationController, curve: Interval(0.5, 1.0)));

    //開始動(dòng)畫
    _animationController.forward();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
              height: _sizeAnimation.value,
              width: _sizeAnimation.value,
              color: _colorAnimation.value),
        ],
      ),
    );
  }

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

效果如下:

我們也可以設(shè)置同時(shí)動(dòng)畫,只需將2個(gè)Interval的值都改為Interval(0.0, 1.0)。

想象下面的場(chǎng)景,一個(gè)紅色的盒子,動(dòng)畫時(shí)長(zhǎng)為6秒,前40%的時(shí)間大小從100->200,然后保持200不變20%的時(shí)間,最后40%的時(shí)間大小從200->300,這種效果通過(guò)TweenSequence實(shí)現(xiàn),代碼如下:

_animation = TweenSequence([
  TweenSequenceItem(
      tween: Tween(begin: 100.0, end: 200.0)
          .chain(CurveTween(curve: Curves.easeIn)),
      weight: 40),
  TweenSequenceItem(tween: ConstantTween<double>(200.0), weight: 20),
  TweenSequenceItem(tween: Tween(begin: 200.0, end: 300.0), weight: 40),
]).animate(_animationController);

weight表示每一個(gè)Tween的權(quán)重。

最終效果如下:

共享動(dòng)畫

Hero是我們常用的過(guò)渡動(dòng)畫,當(dāng)用戶點(diǎn)擊一張圖片,切換到另一個(gè)頁(yè)面時(shí),這個(gè)頁(yè)面也有此圖,那么使用Hero組件就在合適不過(guò)了,先看下Hero的效果圖:

上面效果實(shí)現(xiàn)的列表頁(yè)面代碼如下:

class HeroDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HeroDemo();
}

class _HeroDemo extends State<HeroDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3, crossAxisSpacing: 5, mainAxisSpacing: 3),
        children: List.generate(10, (index) {
          if (index == 6) {
            return InkWell(
              onTap: () {
                Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (context) => new _Hero1Demo()));
              },
              child: Hero(
                tag: 'hero',
                child: Container(
                  child: Image.asset(
                    'images/bird.png',
                    fit: BoxFit.fitWidth,
                  ),
                ),
              ),
            );
          }
          return Container(
            color: Colors.red,
          );
        }),
      ),
    );
  }
}

第二個(gè)頁(yè)面代碼如下:

class _Hero1Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
          alignment: Alignment.topCenter,
          child: Hero(
            tag: 'hero',
            child: Container(
              child: Image.asset(
                'images/bird.png',
              ),
            ),
          )),
    );
  }
}

2個(gè)頁(yè)面都有Hero控件,且tag參數(shù)一致。

路由動(dòng)畫

轉(zhuǎn)場(chǎng) 就是從當(dāng)前頁(yè)面跳轉(zhuǎn)到另一個(gè)頁(yè)面,跳轉(zhuǎn)頁(yè)面在 Flutter 中通過(guò) Navigator,跳轉(zhuǎn)到新頁(yè)面如下:

Navigator.push(context, MaterialPageRoute(builder: (context) {
  return _TwoPage();
}));

回退到前一個(gè)頁(yè)面:

Navigator.pop(context);

Flutter 提供了兩個(gè)轉(zhuǎn)場(chǎng)動(dòng)畫,分別為 MaterialPageRouteCupertinoPageRoute,MaterialPageRoute 根據(jù)不同的平臺(tái)顯示不同的效果,Android效果為從下到上,iOS效果為從左到右。CupertinoPageRoute 不分平臺(tái),都是從左到右。

使用 MaterialPageRoute 案例如下:

class NavigationAnimation extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: OutlineButton(
          child: Text('跳轉(zhuǎn)'),
          onPressed: () {
            Navigator.push(context, CupertinoPageRoute(builder: (context) {
              return _TwoPage();
            }));
          },
        ),
      ),
    );
  }
}

class _TwoPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        color: Colors.blue,
      ),
    );
  }
}

iOS效果:

如果要自定義轉(zhuǎn)場(chǎng)動(dòng)畫如何做?

自定義任何組件都是一樣的,如果系統(tǒng)有類似的,直接看源代碼是如何實(shí)現(xiàn)的,然后按照它的模版自定義組件。

回到正題,看 MaterialPageRoute 的繼承關(guān)系:

PageRoute 的繼承關(guān)系:

MaterialPageRoute 和 CupertinoPageRoute 都是繼承PageRoute,所以重點(diǎn)是 PageRoute,PageRoute 是一個(gè)抽象類,其子類還有一個(gè) PageRouteBuilder,看其名字就知道這是一個(gè)可以自定義動(dòng)畫效果,PageRouteBuilder源代碼:

pageBuilder 表示跳轉(zhuǎn)的頁(yè)面。

transitionsBuilder 表示頁(yè)面的動(dòng)畫效果,默認(rèn)值代碼:

Widget _defaultTransitionsBuilder(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
  return child;
}

通過(guò)源代碼發(fā)現(xiàn),默認(rèn)情況下沒(méi)有動(dòng)畫效果。

自定義轉(zhuǎn)場(chǎng)動(dòng)畫只需修改transitionsBuilder即可:

Navigator.push(
    context,
    PageRouteBuilder(pageBuilder: (
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
    ) {
      return _TwoPage();
    }, transitionsBuilder: (BuildContext context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
        Widget child) {
      return SlideTransition(
        position: Tween(begin: Offset(-1, 0), end: Offset(0, 0))
            .animate(animation),
        child: child,
      );
    }));

將其封裝,方便使用:

class LeftToRightPageRoute extends PageRouteBuilder {
  final Widget newPage;

  LeftToRightPageRoute(this.newPage)
      : super(
          pageBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) =>
              newPage,
          transitionsBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
          ) =>
              SlideTransition(
            position: Tween(begin: Offset(-1, 0), end: Offset(0, 0))
                .animate(animation),
            child: child,
          ),
        );
}

使用:

Navigator.push(context, LeftToRightPageRoute(_TwoPage()));

不僅是這些平移動(dòng)畫,前面所學(xué)的旋轉(zhuǎn)、縮放等動(dòng)畫直接替換 SlideTransition 即可。

上面的動(dòng)畫只對(duì)新的頁(yè)面進(jìn)行了動(dòng)畫,如果想實(shí)現(xiàn)當(dāng)前頁(yè)面被新頁(yè)面從頂部頂出的效果,實(shí)現(xiàn)方式如下:

class CustomPageRoute extends PageRouteBuilder {
  final Widget currentPage;
  final Widget newPage;

  CustomPageRoute(this.currentPage, this.newPage)
      : super(
          pageBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) =>
              currentPage,
          transitionsBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
          ) =>
              Stack(
            children: <Widget>[
              SlideTransition(
                position: new Tween<Offset>(
                  begin: const Offset(0, 0),
                  end: const Offset(0, -1),
                ).animate(animation),
                child: currentPage,
              ),
              SlideTransition(
                position: new Tween<Offset>(
                  begin: const Offset(0, 1),
                  end: Offset(0, 0),
                ).animate(animation),
                child: newPage,
              )
            ],
          ),
        );
}

本質(zhì)就是對(duì)兩個(gè)頁(yè)面做動(dòng)畫處理,使用:

Navigator.push(context, CustomPageRoute(this, _TwoPage()));

除了自定義路由動(dòng)畫,在 Flutter 1.17 發(fā)布大會(huì)上,F(xiàn)lutter 團(tuán)隊(duì)還發(fā)布了新的 Animations 軟件包,該軟件包提供了實(shí)現(xiàn)新的 Material motion 規(guī)范的預(yù)構(gòu)建動(dòng)畫。

里面提供了一系列動(dòng)畫,部分效果:



詳情:https://juejin.im/post/6847902223909781511

交流

老孟Flutter博客地址(330個(gè)控件用法):http://laomengit.com

歡迎加入Flutter交流群(微信:laomengit)、關(guān)注公眾號(hào)【老孟Flutter】:

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

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