在上一章中,学习了如何使用Animater来完成一个自动动画的效果,但是会有一个局限性,那就是使用Animater后它的自组件并不能有同样的动画效果,所以今天来学习在多个不同组件中使用的动画效果:
使用关键词
AnimatedSwitcher:这是用于两个组件之间进行切换的动画效
class MyApp1 extends StatefulWidget {
const MyApp1({Key? key}) : super(key: key);
@override
State<MyApp1> createState() => _MyApp1State();
}
bool a = false;
class _MyApp1State extends State<MyApp1> {
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedSwitcher(
duration: Duration(seconds: 5), //这是一个必传参数,持续时间五秒
child: a == false
? Text(
"w",
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.bold,
fontSize: 40),
)
: Container(
width: 40,
height: 40,
color: Colors.blue.withOpacity(.2),
)),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlatButton(
onPressed: () {
setState(() {
a = !a;
});
},
child: Text("点击切换文字"))//点击切换后,就会有动画效果了
],
)
],
),
);
}
}
但是这里需要注意一点,必须是不同类型的组件,例如如果一开始是一个Text,那么改变后的如果也是Text那是没有作用的.改前和改后必须是两个不同的组件才可以。这是Flutter优化的问题,Flutter认为,在child后面的组件,如果和改变前一样,它会认为你没有改变组件.而是同一个组件
那么如果想要文字切换该如何写呢?其实也比较简单有两种方法
1.只需要在其中一个外面套另外一个组件就可以了,现在演示一下:
class MyApp1 extends StatefulWidget {
const MyApp1({Key? key}) : super(key: key);
@override
State<MyApp1> createState() => _MyApp1State();
}
bool a = false;
class _MyApp1State extends State<MyApp1> {
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedSwitcher(
duration: Duration(seconds: 3), //这是一个必传参数,持续时间三秒
child: a == false
? Text(
"w",
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.bold,
fontSize: 40),
)
: SizedBox(
child: Text(
"m",
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
fontSize: 40),
),
)),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlatButton(
onPressed: () {
setState(() {
a = !a;
});
},
child: Text("点击切换文字"))
],
)
],
),
);
}
}
这样就可以进行同类型的切换了
2.就是使用key了
class MyApp1 extends StatefulWidget {
const MyApp1({Key? key}) : super(key: key);
@override
State<MyApp1> createState() => _MyApp1State();
}
bool a = false;
class _MyApp1State extends State<MyApp1> {
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedSwitcher(
duration: Duration(seconds: 3), //这是一个必传参数,持续时间三秒
child: a == false
? Text(
"w",
key: ValueKey(1),
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.bold,
fontSize: 40),
)
: Text(
"m",
key: ValueKey(2),
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
fontSize: 40),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlatButton(
onPressed: () {
setState(() {
a = !a;
});
},
child: Text("点击切换文字"))
],
)
],
),
);
}
}
使用Key值来告诉Flutter,他们两个不是同一个组件
最后一个有意思的东西就是,如果child后面跟的是null那么它就是一个渐渐消失的动画
这就是AnimatedSwitcher动画组件的学习了