要让AnimatedSwitcher正常工作并显示动画效果,您需要按照以下步骤进行操作:
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State {
// 状态变量
bool _isSwitched = false;
@override
Widget build(BuildContext context) {
return Column(
children: [
// 使用AnimatedSwitcher包装需要切换的小部件
AnimatedSwitcher(
duration: Duration(milliseconds: 500), // 设置动画持续时间
child: _isSwitched ? WidgetA() : WidgetB(),
),
ElevatedButton(
child: Text('切换'),
onPressed: () {
setState(() {
_isSwitched = !_isSwitched; // 切换状态
});
},
),
],
);
}
}
class WidgetA extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
key: ValueKey('widgetA'), // 使用不同的key
child: Text('Widget A'),
);
}
}
class WidgetB extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
key: ValueKey('widgetB'), // 使用不同的key
child: Text('Widget B'),
);
}
}
通过这些步骤,您应该能够在切换AnimatedSwitcher的子小部件时看到动画效果。