Flutter 无限滚动组件实现ListView 方法:


dart
Widget _buildSroll() {
return Container(
height: 30,
width: double.infinity,
child: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(
scrollbars: false, // 隐藏滚动条
),
child: ListView.builder(
controller: _scrollController,
scrollDirection: Axis.vertical,
physics: NeverScrollableScrollPhysics(), // 禁止用户手动滚动
itemCount: notifications.length * 100, // 实现无限循环效果
itemBuilder: (context, index) {
int realIndex = index % notifications.length;
return Container(
height: 30,
padding: EdgeInsets.symmetric(horizontal: 15),
alignment: Alignment.centerLeft,
child: Row(
children: [
Icon(Icons.notifications_active, size: 14, color: Colors.red),
SizedBox(width: 8),
Text(
notifications[realIndex],
style: TextStyle(fontSize: 12, color: Colors.black87),
),
],
),
);
},
),
),
);
}
dart
void _startAutoScroll() {
_scrollTimer = Timer.periodic(Duration(seconds: 2), (timer) {
if (_scrollController != null && _scrollController!.hasClients) {
// 每次滚动一个完整的通知高度 (30px)
_scrollController!.animateTo(
_scrollController!.offset + 30,
duration: Duration(milliseconds: 500),
curve: Curves.easeInOut,
);
}
});
}
dart
ScrollController? _scrollController;
Timer? _scrollTimer;
final List<String> notifications = [
"春节特惠:全场酒店8折起",
"新用户专享:首单立减100元",
"限时活动:预订即送早餐",
"会员福利:积分兑换优惠券",
];
@override
void initState() {
// TODO: implement initState
super.initState();
_ scrollController = ScrollController();
_startAutoScroll();
}
@override
void dispose() {
_scrollTimer?.cancel();
_scrollController?.dispose();
super.dispose();
}