除了上章讲到的使用方法,其实还有一种特殊的方法:
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(
transitionBuilder: (child, animater) {
return FadeTransition(//这里就是默认的参数,也就是如果没有写这个的话
//就会默认是渐变消失的形式,除此之外我们还可以使用别的方法
opacity: animater,
child: child,
);
},
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("点击切换文字"))
],
)
],
),
);
}
}
例如旋转改变:
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(
transitionBuilder: (child, animater) {
return RotationTransition(//旋转改变
turns: animater,//旋转的的次数
child: child,
);
},
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("点击切换文字"))
],
)
],
),
);
}
}
或者是换一种方式渐变:
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(
transitionBuilder: (child, animater) {
return ScaleTransition(
//旋转改变
scale: animater, //旋转的的次数
child: child,
);
},
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("点击切换文字"))
],
)
],
),
);
}
}