AnimatedSwitcher not working as intended? Widget changing but no animation
If the new widget you're switching in, is the same type as previous widget, set the key
property to another value to get that animation
for example, this AnimatedSwitcher
doesn't work:
AnimatedSwitcher(
duration: const Duration(milliseconds: 1000),
child: (condition)
? Container(
width: 100,
height: 100,
color: Colors.red,
)
: Container(
width: 100,
height: 100,
color: Colors.blue,
),
);
Because we want to switch between two Container
s, and AnimatedSwitcher
can't understand the difference of them, so it doesn't animate their switch.
If we set different key
property in those Container
s, then AnimatedSwitcher
can understand they are different and does animate their switch.
Just like this:
AnimatedSwitcher(
duration: const Duration(milliseconds: 1000),
child: (condition)
? Container(
key: ValueKey<int>(0),
width: 100,
height: 100,
color: Colors.red,
)
: Container(
key: ValueKey<int>(1),
width: 100,
height: 100,
color: Colors.blue,
),
);
you can try this
class _AniSwitchState extends State<AniSwitch> {
Widget calledWidget;
@override
Widget build(BuildContext context) {
void switchPage(int newNumber) {
if (newNumber == 1) {
setState(() {calledWidget = WelcomeScreen();},);
} else if (newNumber == 2) {
setState(() {calledWidget = LearnMoreScreen();},);}
}
if (calledWidget == null) {
switchPage(1);
}
return Column(
children: <Widget>[
AnimatedSwitcher(
duration: Duration(milliseconds: 2000),
child: calledWidget
),
RaisedButton(
child: const Text('Increment'),
onPressed: () {
setState(() {
switchPage(2);
});
},
),
],
);
}
}
class WelcomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text("Welcome"),
],
);
}
}
class LearnMoreScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text("hello world"),
],
);
}
}