目标:按下一个按钮,让它切换到另一个带有动画过渡的页面。
为此,我使用了 AnimatedSwitcher。
下面是我的代码:
class WelcomeScreenSwitcher extends State<RandomWords>{
Widget calledWidget;
void switchPage(int newNumber, context) {
if (newNumber == 1) {
setState(() {calledWidget = welcomeScreen(context);},);
} else if (newNumber == 2) {
setState(() {calledWidget = learnMoreScreen(context);},);}
}
@override
Widget build(BuildContext context) {
if (calledWidget == null) {
switchPage(1, context);
}
return AnimatedSwitcher(
duration: Duration(milliseconds: 5000),
child: calledWidget,
);
Widget welcomeScreen(context){
return Scaffold({body: Column(children: [
RaisedButton(onPressed: () {switchPage(2, context);}, child: Text('B'),),],
);
});
}
Widget learnMoreScreen(context){
return Scaffold({body: Column(children: [
RaisedButton(onPressed: () {switchPage(2, context);}, child: Text('B'),),],
);
});
}
}
代码是功能性的。它确实会在两个页面之间切换,但没有相应的动画。
在开发过程中的某个时候,我得到了动画,但后来它就停止了,我也不知道为什么。我不记得有任何关于我如何调用 AnimatedSwitcher 的具体更改。
如果它有任何用处,热重载也不再起作用。我需要重新启动应用程序才能进行任何更改注册。在开始处理 AnimatedSwitcher 之前,它曾经正常运行。
最佳答案
如果您要切换的新小部件与之前的小部件类型相同,请将 key
属性设置为另一个值以获取该动画
例如,这个 AnimatedSwitcher
不起作用:
AnimatedSwitcher(
duration: const Duration(milliseconds: 1000),
child: (condition)
? Container(
width: 100,
height: 100,
color: Colors.red,
)
: Container(
width: 100,
height: 100,
color: Colors.blue,
),
);
因为我们要在两个Container
之间切换,而AnimatedSwitcher
无法理解它们之间的区别,所以它不会为它们的切换设置动画。
如果我们在这些 Container
中设置不同的 key
属性,那么 AnimatedSwitcher
可以理解它们的不同并为它们的开关设置动画。
就像这样:
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,
),
);
关于flutter - AnimatedSwitcher 没有按预期工作?小部件更改但没有动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57548253/