Flutter共享元素Hero Animation无法与自定义ModalRoute一起使用

时间:2018-10-06 10:13:35

标签: flutter flutter-animation

为了获得类似“模态”的效果(当将页面推入当前页面的顶部时,其背景为黑色且具有足够的透明度,因此您可以在背景中看到后面的页面)。

我正在使用ModalRoute类在当前页面的顶部显示覆盖小部件。

我的问题是::进入我的TestOverlay页面时,仅显示fadeIn动画,而不显示Shared Element Hero动画。

后面的页面有一个Hero(tag: "111", child: Text("Test"))小部件,当我调用Navigator.of(context).push(TestOverlay());时,只有FadeInis具有动画效果,并且共享元素过渡不起作用。.::

有人知道为什么吗?

谢谢!

class TestOverlay extends ModalRoute<void> {
  TestOverlay();

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

  @override
  bool get opaque => false;

  @override
  bool get barrierDismissible => false;

  @override
  Color get barrierColor => Colors.black.withOpacity(0.7);

  @override
  String get barrierLabel => null;

  @override
  bool get maintainState => true;

  @override
  Widget buildPage(
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      ) {
    // This makes sure that text and other content follows the material style
    return Material(
      type: MaterialType.transparency,
      // make sure that the overlay content is not cut off
      child: GestureDetector(
        onTap: () {
          Navigator.pop(context);
        },
        behavior: HitTestBehavior.opaque,
        child: SafeArea(
          child: _buildOverlayContent(context),
        ),
      ),
    );
  }

  Widget _buildOverlayContent(BuildContext context) {
    return Center(
      child: Hero(tag: "111", Text("Test"))
    );
  }

  @override
  Widget buildTransitions(
      BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    // You can add your own animations for the overlay content
    return FadeTransition(
      opacity: animation,
      child: ScaleTransition(
        scale: animation,
        child: child,
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

改为使用PageRoute

class TestOverlay extends PageRoute<void> {
  TestOverlay({
    @required this.builder,
    RouteSettings settings,
  })  : assert(builder != null),
        super(settings: settings);

  final WidgetBuilder builder;

  @override
  bool get opaque => false;

  @override
  Color get barrierColor => null;

  @override
  String get barrierLabel => null;

  @override
  bool get maintainState => true;

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

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    final result = builder(context);
    return FadeTransition(
      opacity: Tween<double>(begin: 0, end: 1).animate(animation),
      child: result,
    );
  }
}