![](https://img.haomeiwen.com/i1341081/b1206c917bcf55c2.gif)
本来是使用第三方CarouselSlider 就能简单完成需求,但是他无法实现宽度自适应,类似多语言的时候,可能有问题,所以自己写了一个。
class TitleSwitcher extends StatefulWidget {
final List<String> titles;
final Duration duration;
final TextStyle? style;
const TitleSwitcher(
{super.key, required this.titles, required this.duration, this.style});
@override
_TitleSwitcherState createState() => _TitleSwitcherState();
}
class _TitleSwitcherState extends State<TitleSwitcher> {
int _currentIndex = 0;
late Timer _timer;
@override
void initState() {
super.initState();
_startTimer();
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
void _startTimer() {
_timer = Timer.periodic(widget.duration, (Timer timer) {
setState(() {
_currentIndex = (_currentIndex + 1) % widget.titles.length;
});
});
}
@override
Widget build(BuildContext context) {
return AnimatedSwitcher(
duration: Duration(seconds: 1),
transitionBuilder: (Widget child, Animation<double> animation) {
final slideInAnimation = Tween<Offset>(
begin: Offset(0, 1),
end: Offset(0, 0),
).animate(animation);
final slideOutAnimation = Tween<Offset>(
begin: Offset(0, -1),
end: Offset(0, 0),
).animate(animation);
if (child.key == ValueKey(_currentIndex)) {
return ClipRect(
child: SlideTransition(
position: slideInAnimation,
child: child,
),
);
} else {
return ClipRect(
child: SlideTransition(
position: slideOutAnimation,
child: child,
),
);
}
},
child: Text(
widget.titles[_currentIndex],
key: ValueKey<int>(_currentIndex),
style: widget.style ?? TextStyle(fontSize: 24),
),
);
}
}
网友评论