Flutter - 路由动画 PageRoute(2020.01.06更新)

页面跳转动画是在开发中经常需要使用到的,根据经验撸了一个动画路由类: AnimationPageRoute.

BUG: 出事了,请暂停使用该路由!经验证发现该路由在页面切出去然后再返回,会导致ExitPage对象的类中的initState(原只会执行一次生命周期),didDependencesChanged重复执行多次!显然这不是我们要的效果!因为往往我们会在initState执行网络调用等一类的操作,如此以来就会导致页面多次调用网络请求等初始化操作
注意:文章最下方有一种另类解决方案!

使用事项:
1.exitPage 可忽略对象,如果不传,则只执行enterPage的动画;
2.exitPage 对象应该是指一个完整的Page页面,不可为某一个部件,否则动画会很怪异;

import 'package:flutter/material.dart';

enum AnimationType {
  /// 从右到左的滑动
  SlideRL,

  /// 从左到右的滑动
  SlideLR,

  /// 从上到下的滑动
  SlideTB,

  /// 从下到上的滑动
  SlideBT,

  /// 透明过渡
  Fade,
}

class AnimationPageRoute extends PageRouteBuilder {
  /// 进入的页面
  Widget enterPage;

  /// 退出的页面
  Widget exitPage;

  AnimationPageRoute({
    @required this.enterPage,
    this.exitPage,
    AnimationType animationType = AnimationType.SlideRL,
    Duration transitionDuration = const Duration(milliseconds: 300),
    bool opaque = true,
    bool barrierDismissible = false,
    Color barrierColor,
    String barrierLabel,
    bool maintainState = true,
  })  : assert(enterPage != null, '参数[enterPage]不能为空!'),
        super(
          transitionDuration: transitionDuration,
          pageBuilder: (BuildContext context, Animation<double> animation,
                  Animation<double> secondaryAnimation) =>
              enterPage,
          transitionsBuilder: (BuildContext context,
                  Animation<double> animation,
                  Animation<double> secondaryAnimation,
                  Widget child) =>
              _getAnimation(enterPage, exitPage, animation,
                  animationType: animationType),
          opaque: opaque,
          barrierColor: barrierColor,
          barrierLabel: barrierLabel,
          maintainState: maintainState,
        );

  static Widget _getAnimation(
      Widget enterPage, Widget exitPage, Animation<double> animation,
      {AnimationType animationType = AnimationType.SlideRL}) {
    List<Widget> _animationWidgets = <Widget>[];
    if (animationType == AnimationType.Fade) {
      _animationWidgets.addAll([
        if (exitPage != null)
          FadeTransition(
              opacity: Tween<double>(begin: 1, end: 0).animate(animation),
              child: exitPage),
        FadeTransition(
            opacity: Tween<double>(begin: 0, end: 1).animate(animation),
            child: enterPage)
      ]);
    } else {
      Offset oBegin, oEnd, iBegin, iEnd;
      if (animationType == AnimationType.SlideBT) {
        oBegin = Offset.zero;
        oEnd = Offset(0, -1);
        iBegin = Offset(0, 1);
        iEnd = Offset.zero;
      } else if (animationType == AnimationType.SlideTB) {
        oBegin = Offset.zero;
        oEnd = Offset(0, 1);
        iBegin = Offset(0, -1);
        iEnd = Offset.zero;
      } else if (animationType == AnimationType.SlideLR) {
        oBegin = Offset.zero;
        oEnd = Offset(1, 0);
        iBegin = Offset(-1, 0);
        iEnd = Offset.zero;
      } else {
        oBegin = Offset.zero;
        oEnd = Offset(-1, 0);
        iBegin = Offset(1, 0);
        iEnd = Offset.zero;
      }
      _animationWidgets.addAll([
        if (exitPage != null)
          SlideTransition(
              position:
                  Tween<Offset>(begin: oBegin, end: oEnd).animate(animation),
              child: exitPage),
        SlideTransition(
            position:
                Tween<Offset>(begin: iBegin, end: iEnd).animate(animation),
            child: enterPage)
      ]);
    }
    return Stack(children: _animationWidgets);
  }
}

一种另类的解决这种问题的方案

使用RenderPaintBoundary把当前页面图像绘制出来,然后设置它为exitPage,方法如下:


  final GlobalKey _repaintBoundaryKey = GlobalKey();

  Future<Image> getScreenImage() async {
    RenderRepaintBoundary renderRepaintBoundary =
        _repaintBoundaryKey.currentContext.findRenderObject();
    UI.Image image = await renderRepaintBoundary.toImage();
    return Image.memory((await image.toByteData(format: UI.ImageByteFormat.png))
        .buffer
        .asUint8List());
  }

 @override
  Widget build(BuildContext context) => RepaintBoundary(
      key: _repaintBoundaryKey,
      child: Scaffold(
          backgroundColor: const Color(0xfff5f5f5),
          appBar: _buildAppBar(),
          body: _buildContentView()));

优化之路,使用Mixin

import 'dart:ui' as Ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:yunnan_season/core/route/animation_page_route.dart';

/// 使用[AnimationPageRoute]需要调用该Mixin
mixin AnimationPageProviderMixin {
  /// 绘制面板关联的GlobalKey对象
  final GlobalKey _repaintBoundaryKey = GlobalKey();

  /// 获取绘制面板中的图像
  Future<RawImage> getUiDrawingImage() async {
    if (_repaintBoundaryKey == null)
      throw Exception('错误:调用该方法前请使用[drawingPad]方法!');
    RenderRepaintBoundary renderBoundary =
        _repaintBoundaryKey.currentContext.findRenderObject();
    return RawImage(
        image: (await renderBoundary.toImage(
            pixelRatio: Ui.window.devicePixelRatio)),
        filterQuality: FilterQuality.high);
  }

  /// 绘画面板
  Widget drawingPad(Widget child) =>
      RepaintBoundary(key: _repaintBoundaryKey, child: child);

  /// 动画路由对象
  AnimationPageRoute<T> animationPageRoute<T>(
    Widget nextPage,
    Widget currentPage, {
    Duration duration = const Duration(milliseconds: 400),
    AnimationType type = AnimationType.SlideRL,
  }) =>
      AnimationPageRoute<T>(
          enterPage: nextPage,
          exitPage: currentPage,
          transitionDuration: duration,
          animationType: type);
}

使用实例:


  void _startWithDrawMainPage() async => Navigator.push(context,
      animationPageRoute(WithDrawMainPage(), (await getUiDrawingImage())));

  @override
  Widget build(BuildContext context) => drawingPad(Scaffold(
      backgroundColor: const Color(0xfff5f5f5),
      appBar: _buildAppBar(),
      body: _buildContentView()));

哈哈,暂时就这样,希望能帮到各位看客!

再次经过多方研究和求证,发现路由页面的切换动画加上CurvedAnimation会生动很多,而且还不会造成异常。因为以前方案都存在缺陷,甚至是报错。经过多次求证,有了如下代码:

简要说明:动画类似iOS的切换动画,ExitPage也具有离开时的动画(但以下代码暂且只提供SlideRL和SlideLR的动画)。更多效果,请研究CurvedAnimation。

// import 'dart:ui' as Ui;

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

final Tween<double> _tweenFade = Tween<double>(begin: 0, end: 1.0);

final Tween<Offset> _primaryTweenSlideFromBottomToTop =
    Tween<Offset>(begin: const Offset(0.0, 1.0), end: Offset.zero);

// final Tween<Offset> _secondaryTweenSlideFromBottomToTop =
//     Tween<Offset>(begin: Offset.zero, end: const Offset(0.0, -1.0));

final Tween<Offset> _primaryTweenSlideFromTopToBottom =
    Tween<Offset>(begin: const Offset(0.0, -1.0), end: Offset.zero);

// final Tween<Offset> _secondaryTweenSlideFromTopToBottom =
//     Tween<Offset>(begin: Offset.zero, end: const Offset(0.0, 1.0));

final Tween<Offset> _primaryTweenSlideFromRightToLeft =
    Tween<Offset>(begin: const Offset(1.0, 0.0), end: Offset.zero);

final Tween<Offset> _secondaryTweenSlideFromRightToLeft =
    Tween<Offset>(begin: Offset.zero, end: const Offset(-1.0, 0.0));

final Tween<Offset> _primaryTweenSlideFromLeftToRight =
    Tween<Offset>(begin: const Offset(-1.0, 0.0), end: Offset.zero);

final Tween<Offset> _secondaryTweenSlideFromLeftToRight =
    Tween<Offset>(begin: Offset.zero, end: const Offset(1.0, 0.0));

/// 动画类型枚举,`SlideRL`,`SlideLR`,`SlideTB`, `SlideBT`, `Fade`
enum AnimationType {
  /// 从右到左的滑动
  SlideRL,

  /// 从左到右的滑动
  SlideLR,

  /// 从上到下的滑动
  SlideTB,

  /// 从下到上的滑动
  SlideBT,

  /// 透明过渡
  Fade,
}

class AnimationPageRoute<T> extends PageRoute<T> {
  AnimationPageRoute({
    @required this.builder,
    this.isExitPageAffectedOrNot = true,
    this.animationType = AnimationType.SlideRL,
    RouteSettings settings,
    this.maintainState = true,
    bool fullscreenDialog = false,
  })  : assert(builder != null),
        assert(isExitPageAffectedOrNot != null),
        assert(animationType != null),
        assert(maintainState != null),
        assert(fullscreenDialog != null),
        assert(opaque),
        super(settings: settings, fullscreenDialog: fullscreenDialog);

  final WidgetBuilder builder;

  /// 该参数只针对当[AnimationType]为[SlideLR]或[SlideRL]新页面及当前页面动画均有效
  final bool isExitPageAffectedOrNot;

  final AnimationType animationType;

  @override
  final bool maintainState;

  @override
  Duration get transitionDuration => const Duration(milliseconds: 1000);

  @override
  Color get barrierColor => null;

  @override
  String get barrierLabel => null;

  @override
  bool canTransitionTo(TransitionRoute<dynamic> nextRoute) =>
      nextRoute is AnimationPageRoute && !nextRoute.fullscreenDialog;

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    final Widget result = builder(context);
    assert(() {
      if (result == null) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary(
              'The builder for route "${settings.name}" returned null.'),
          ErrorDescription('Route builders must never return null.')
        ]);
      }
      return true;
    }());
    return Semantics(
        scopesRoute: true, explicitChildNodes: true, child: result);
  }

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation, Widget child) {
    if (animationType == AnimationType.Fade)
      FadeTransition(
          opacity: CurvedAnimation(
            parent: animation,
            curve: Curves.linearToEaseOut,
            reverseCurve: Curves.easeInToLinear,
          ).drive(_tweenFade),
          child: child);
    final TextDirection textDirection = Directionality.of(context);
    Tween<Offset> primaryTween = _primaryTweenSlideFromRightToLeft,
        secondTween = _secondaryTweenSlideFromRightToLeft;
    Cubic curve = Curves.linearToEaseOut, reverseCurve = Curves.easeInToLinear;
    if (animationType == AnimationType.SlideBT) {
      primaryTween = _primaryTweenSlideFromBottomToTop;
    } else if (animationType == AnimationType.SlideTB) {
      primaryTween = _primaryTweenSlideFromTopToBottom;
    } else if (animationType == AnimationType.SlideLR) {
      primaryTween = _primaryTweenSlideFromLeftToRight;
      secondTween = _secondaryTweenSlideFromLeftToRight;
      curve = Curves.fastOutSlowIn;
      reverseCurve = Curves.easeOutCubic;
    }
    Widget enterAnimWidget = SlideTransition(
        position: CurvedAnimation(
          parent: animation,
          curve: curve,
          reverseCurve: reverseCurve,
        ).drive(primaryTween),
        textDirection: textDirection,
        child: child);
    if (isExitPageAffectedOrNot != true ||
        ([AnimationType.SlideTB, AnimationType.SlideBT]
            .contains(animationType))) return enterAnimWidget;
    return SlideTransition(
        position: CurvedAnimation(
          parent: secondaryAnimation,
          curve: curve,
          reverseCurve: reverseCurve,
        ).drive(secondTween),
        textDirection: textDirection,
        child: enterAnimWidget);
  }

  @override
  String get debugLabel => '${super.debugLabel}(${settings.name})';
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容