主题
自动无缝向上滚动
dart
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Continuous Seamless Auto Scrolling List'),
),
body: const Center(
child: SizedBox(
height: 200, // 固定高度
child: InfiniteListView(),
),
),
),
);
}
}
class InfiniteListView extends StatefulWidget {
const InfiniteListView({super.key});
@override
State<InfiniteListView> createState() => _InfiniteListViewState();
}
class _InfiniteListViewState extends State<InfiniteListView> {
late ScrollController _scrollController;
final List<String> items = List.generate(20, (index) => 'Item $index');
late Timer _timer;
@override
void initState() {
super.initState();
_scrollController = ScrollController();
_timer = Timer.periodic(const Duration(milliseconds: 30), (_) {
_scrollList();
});
}
@override
Widget build(BuildContext context) {
return ListView.builder(
controller: _scrollController,
itemCount: items.length * 3, // 无限循环
itemBuilder: (context, index) {
final itemIndex = index % items.length;
return ListTile(
title: Text(items[itemIndex]),
);
},
);
}
void _scrollList() {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.offset + 3, // 滚动速度
duration: const Duration(milliseconds: 30), // 滚动时间间隔
curve: Curves.linear,
);
// 检查是否需要重置滚动位置
if (_scrollController.position.maxScrollExtent <= _scrollController.offset) {
_scrollController.jumpTo(0);
}
}
}
@override
void dispose() {
_scrollController.dispose();
_timer.cancel();
super.dispose();
}
}