Flutter - 在两个不同大小的小部件之间滑动过渡

Flutter - Slide Transition between two different sized widgets

我正尝试在小部件之间制作动画,如下所示:

AnimatedSwitcher(
                  duration: const Duration(seconds: 1),
                  transitionBuilder: (Widget child, Animation<double> animation) {
                    return SlideTransition(
                      position: Tween(
                          begin: Offset(1.0, 0.0),
                          end: Offset(0.0, 0.0),)
                          .animate(animation),
                      child: child,
                    );
                  },
                  child: Provider.of<UserWidgets>(context, listen: false).renderWidget(context),
                ),

这工作正常,但由于 OffSet,对于两个不同大小的小部件,它不流畅。

尝试将您的两个子窗口小部件包装在一个 Align 窗口小部件中,

child: Align(
  alignment: Alignment.topCenter,
  child: Provider.of<UserWidgets>(context, listen: false).renderWidget(context),
)

这应该确保您的旧子项和新子项在设置动画时始终与 topCenter 对齐。

这是完整的工作示例。

class Switcher extends StatefulWidget {
  State<StatefulWidget> createState() => SwitcherS();
}

class SwitcherS extends State<Switcher> {
  bool state = false;

  buildChild (index) => Align(
    alignment: Alignment.topCenter,
    child: Container(
      width: index == 0 ? 100 : 150,
      height: index == 0 ? 200 : 150,
      color:index == 0 ? Colors.deepPurple : Colors.deepOrange,
    ),
   key: ValueKey('$index'));

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => setState(() { state = !state; }),
      child: Padding(
        padding: EdgeInsets.all(24),
        child: AnimatedSwitcher(
          duration: const Duration(seconds: 1),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return SlideTransition(
              position: Tween(
                begin: Offset(1.0, 1.0),
                end: Offset(0.0, 0.0),
              ).animate(animation),
              child: child,
            );
          },
          child: buildChild(state ? 0 : 1),
      ),
    );
  }
}