简体   繁体   English

英雄小部件过渡与其他动画冲突

[英]Hero widget transition conflict with other animations

I'm trying to achieve the Hero & shake upright animation result attached gif here.我正在努力实现 Hero & shake upright animation 结果附加gif在这里。 This is the result I got so far.这是我到目前为止得到的结果

Seems like the Hero widget conflicts with the animation I've applied.似乎英雄小部件与我申请的 animation 冲突。 It seems to be working for the 200 & 300 card.它似乎适用于200300卡。 But when 100 is tapped, it seems to be working differently.但是当点击100时,它的工作方式似乎有所不同。 Attached below are the code for the demo above.下面附上上面演示的代码。

Tried using WidgetsBinding.instance.addPostFrameCallback and SchedulerBinding.instance.addPersistentFrameCallback .尝试使用WidgetsBinding.instance.addPostFrameCallbackSchedulerBinding.instance.addPersistentFrameCallback

Is there any way to get the expected result instead of using the code I've used?有什么方法可以得到预期的结果而不是使用我用过的代码吗?

dummy_data.dart虚拟数据.dart

class _DummyData {
  final IconData icons;
  final Color colors;
  final String backText;

  const _DummyData(this.icons, this.colors, this.backText);
}

const List<_DummyData> _datas = [
  _DummyData(Icons.abc, Colors.blue, '100'),
  _DummyData(Icons.alarm, Colors.red, '200'),
  _DummyData(Icons.shop, Colors.green, '300'),
];

playground_list.dart playground_list.dart


class PlayGroundList extends StatelessWidget {
  const PlayGroundList({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: CustomScrollView(
        slivers: [
          const SliverToBoxAdapter(child: SizedBox(height: 50)),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              childCount: _datas.length,
              (context, index) => PlayGroundCardWidget(dummy: _datas[index]),
            ),
          ),
        ],
      ),
    );
  }
}

playground_card_widget.dart playground_card_widget.dart

class PlayGroundCardWidget extends StatelessWidget {
  final _DummyData dummy;

  const PlayGroundCardWidget({super.key, required this.dummy});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 5.w, vertical: 1.5.h),
      height: 350,
      child: GestureDetector(
        onTap: () => Navigator.push(
          context,
          PageRouteBuilder(
            transitionsBuilder: (context, animation, _, child) =>
                FadeTransition(
              opacity: Tween(
                begin: 0.0,
                end: 1.0,
              ).chain(CurveTween(curve: Curves.ease)).animate(animation),
              child: child,
            ),
            pageBuilder: (context, _, __) => PlayGroundDetail(dummy: dummy),
          ),
        ),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned.fill(
              child: Hero(
                tag: dummy.colors.value,
                child: Material(color: dummy.colors),
              ),
            ),
            Align(
              alignment: Alignment.topCenter,
              child: Hero(
                tag: dummy.backText,
                child: Material(
                  color: Colors.transparent,
                  child: Text(
                    dummy.backText,
                    textAlign: TextAlign.center,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.black,
                      fontSize: 140.0,
                    ),
                  ),
                ),
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: 3.h),
                Expanded(
                  flex: 12,
                  child: Hero(
                    tag: dummy.icons,
                    child: Icon(dummy.icons, size: 60.0),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

playground_detail.dart playground_detail.dart

const _shakeDuration = Duration(milliseconds: 900);

class PlayGroundDetail extends StatefulWidget {
  final _DummyData dummy;

  const PlayGroundDetail({super.key, required this.dummy});

  @override
  State<PlayGroundDetail> createState() => _PlayGroundDetailState();
}

class _PlayGroundDetailState extends State<PlayGroundDetail>
    with TickerProviderStateMixin {
  late final PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          CustomScrollView(
            slivers: [
              const SliverToBoxAdapter(child: SizedBox(height: 50)),
              SliverToBoxAdapter(
                child: SizedBox(
                  height: 350,
                  child: Stack(
                    children: [
                      Positioned.fill(
                        child: Hero(
                          tag: widget.dummy.colors.value,
                          child: Material(color: widget.dummy.colors),
                        ),
                      ),
                      Align(
                        alignment: Alignment.topCenter,
                        child: Hero(
                          tag: widget.dummy.backText,
                          child: Material(
                            color: Colors.transparent,
                            child: ShakeTransitionWidget(
                              axis: Axis.vertical,
                              duration: _shakeDuration,
                              offset: 30,
                              child: Text(
                                widget.dummy.backText,
                                textAlign: TextAlign.center,
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                  color: Colors.black,
                                  fontSize: 140.0,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                      Center(
                        child: Hero(
                          tag: widget.dummy.icons,
                          child: ShakeTransitionWidget(
                            axis: Axis.vertical,
                            offset: 5,
                            duration: _shakeDuration,
                            child: Icon(widget.dummy.icons, size: 60.0),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

shake_transition_widget.dart shake_transition_widget.dart

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

class ShakeTransitionWidget extends StatefulWidget {
  final Widget child;
  final Duration duration;
  final double offset;
  final Axis axis;

  const ShakeTransitionWidget({
    super.key,
    required this.child,
    required this.duration,
    required this.offset,
    required this.axis,
  });

  @override
  State<ShakeTransitionWidget> createState() => _ShakeTransitionWidgetState();
}

class _ShakeTransitionWidgetState extends State<ShakeTransitionWidget>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: widget.duration,
    );
    _animation = Tween(
      begin: 1.0,
      end: 0.0,
    ).chain(CurveTween(curve: Curves.elasticOut)).animate(_controller);
    // Tried this.
    // WidgetsBinding.instance.addPostFrameCallback((_) => _controller.forward());
    if (SchedulerBinding.instance.schedulerPhase ==
        SchedulerPhase.persistentCallbacks) {
      _controller.forward();
    }
    SchedulerBinding.instance.addPersistentFrameCallback((timeStamp) {});
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (ctx, _) => Transform.translate(
        offset: widget.axis == Axis.horizontal
            ? Offset(_animation.value * widget.offset, 0.0)
            : Offset(0.0, _animation.value * widget.offset),
        child: widget.child,
      ),
    );
  }
}

Wrap your Hero widget with ShakeTransitionWidget instead of the other way around:ShakeTransitionWidget包装你的Hero小部件,而不是相反:

// ... Hero is the child, not the parent
ShakeTransitionWidget(
  axis: Axis.vertical,
  duration: _shakeDuration,
  offset: 30,
  child: Hero(
  tag: widget.dummy.backText,
// ...

Now inside the initState() of _ShakeTransitionWidgetState simply call _controller.forward() without any SchedulerBinding or WidgetsBinding .现在,在 _ShakeTransitionWidgetState 的_ShakeTransitionWidgetState initState()中,只需调用_controller.forward()即可,无需任何SchedulerBindingWidgetsBinding

As a rule of thumb, usually the Hero and its children should not change from page to page.根据经验,英雄及其子项通常不应逐页更改。 Instead add modifications to the parent widgets.而是向父小部件添加修改。

See gif .动图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM