当页面刚进来的时候,AnimatedSwitch会执行一个动画,通过使用定时器来控制切换下一张图片的动画, 给AnimatedSwitch设置一个key UniqueKey 一个随机的key, 这样AnimatedSwitch才能感受到子元素需要执行动画,因为key改变了, 这里面可以使用多种动画,可以按照需求修改相应的参数,
,当用户刚进入页面时,动画执行一次,这边有三个指示器用户点击指示器通过索引赋值, 切换至相应的图片,然后将_timer 重新赋值,这样就不会当用户点击的时候,上一个时间就到了立马切换动画
import 'dart:async';
import 'package:flutter/material.dart';
class BannerScreen extends StatefulWidget {
const BannerScreen({Key? key}) : super(key: key);
@override
State<BannerScreen> createState() => _BannerScreenState();
}
class _BannerScreenState extends State<BannerScreen> with SingleTickerProviderStateMixin{
List<String> _banners = [
"banner1.png",
"banner2.png",
"banner3.png",
];
int currentIndex = 0;
late Timer? _timer;
void _currentChange(){
_timer = Timer.periodic(Duration(seconds: 5), (timer) {
currentIndex++;
if(currentIndex > 2){
currentIndex = 0;
}
setState(() {
});
});
}
@override
void initState() {
_currentChange();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: double.infinity,
width: double.infinity,
child: Column(
children: [
SizedBox(height: 30),
AnimatedSwitcher(
duration: Duration(milliseconds: 500),
transitionBuilder: (child,animation){
return SlideTransition(position: Tween<Offset>(
begin: Offset(1.0,0.0),
end: Offset.zero
).animate(animation),child: FadeTransition(
opacity: animation,
child: child,
),);
},
child: Container(
height: 200,
width: 400,
key: UniqueKey(),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
image:DecorationImage(
image: AssetImage("assets/${_banners[currentIndex]}"),fit: BoxFit.cover
)
),
alignment: Alignment.bottomCenter,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(_banners.length, (index){
return Padding(
padding: EdgeInsets.only(bottom: 10),
child: GestureDetector(
onTap: (){
setState(() {
currentIndex = index;
_timer!.cancel();
_timer = null;
_currentChange();
});
},
child: Container(
height: 10,
width: 10,
margin: EdgeInsets.only(right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: currentIndex == index ? Colors.red : Colors.grey
),
),
),
);
}),
),
),
)
],
),
),
);
}
}
使用AnimatedSwitch 也是可以作为启动动画,通常会使用TweenAnimationBuilder来作为起始动画,使用TweenAnimationBuilder
的好处是它简化了动画的创建过程。只需要指定起始值、结束值、动画持续时间以及所需的构建函数,TweenAnimationBuilder
将自动生成需要的动画代码。两者的区别是如果你需要一个简单的接口来实现过渡动画,包括启动动画,那么使用 AnimatedSwitcher
是一个较为方便的选择。如果您需要更高度的灵活性和自定义性,则可以选择使用 TweenAnimationBuilder
。
TweenAnimationBuilder(
duration: Duration(milliseconds: 500),
tween: Tween(begin: 0.25,end: 1),
builder: (_,value,child){
return Transform.scale(scale: double.parse(value.toString()),child: child);
},
child: Text("我是大帅比",style: TextStyle(fontSize: 50,color: Colors.black),),
)