Flutter圈子FlutterFlutter

Flutter - 路由动画 PageRoute(2020.01

2019-11-27  本文已影响0人  Cosecant

页面跳转动画是在开发中经常需要使用到的,根据经验撸了一个动画路由类: 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})';
}
上一篇 下一篇

猜你喜欢

热点阅读