5

I am trying to animate between widgets as follows:

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),
                ),

This works fine but for two different sized widgets its not smooth because of OffSet. GIF

Ashim Bhadra
  • 268
  • 4
  • 14

1 Answers1

5

Try wrapping both your child widgets inside an Align widget like this,

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

This should ensure that both your old and new children are always aligned to the topCenter while animating.

Here is the full working example.

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),
      ),
    );
  }
}
Nisanth Reddy
  • 5,967
  • 1
  • 11
  • 29
  • That made animation go away – Ashim Bhadra May 23 '21 at 06:21
  • could you provide your full code using a https://pastebin.com/. I have created a minimal example and it was working. – Nisanth Reddy May 23 '21 at 06:22
  • Its the same that I included in the question. renderWidget just returns two containers of different height and colors. – Ashim Bhadra May 23 '21 at 06:24
  • I have updated my answer with the full working code. If you are just returning two different container, you shouldn't be having an issue. Otherwise, update your post with full code. Try running my code in your device. – Nisanth Reddy May 23 '21 at 06:42