Skip to content

Instantly share code, notes, and snippets.

@Muhammad-Haris-2
Last active March 7, 2025 16:24
Show Gist options
  • Select an option

  • Save Muhammad-Haris-2/f109ca363f51f1bdfa605d222ce4e5df to your computer and use it in GitHub Desktop.

Select an option

Save Muhammad-Haris-2/f109ca363f51f1bdfa605d222ce4e5df to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
class MarqueeScroll extends StatefulWidget {
final List<Widget> items;
final bool scrollRight; // true for right, false for left
final Duration duration;
const MarqueeScroll({
super.key,
required this.items,
this.scrollRight = false,
this.duration = const Duration(seconds: 10),
});
@override
State<MarqueeScroll> createState() => _MarqueeScrollState();
}
class _MarqueeScrollState extends State<MarqueeScroll> with SingleTickerProviderStateMixin {
late ScrollController _scrollController;
late AnimationController _animationController;
@override
void initState() {
super.initState();
_scrollController = ScrollController();
_animationController = AnimationController(
vsync: this,
duration: widget.duration,
)..repeat();
_animationController.addListener(() {
if (_scrollController.hasClients) {
double offsetChange = widget.scrollRight ? -1 : 1;
_scrollController.jumpTo(_scrollController.offset + offsetChange);
// Reset scroll when reaching the end
if (_scrollController.offset <= 0 && widget.scrollRight) {
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);
} else if (_scrollController.offset >= _scrollController.position.maxScrollExtent && !widget.scrollRight) {
_scrollController.jumpTo(0);
}
}
});
}
@override
void dispose() {
_scrollController.dispose();
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
List<Widget> loopedItems = [...widget.items, ...widget.items]; // Duplicate for seamless looping
return SizedBox(
height: 100,
child: ListView.builder(
controller: _scrollController,
scrollDirection: Axis.horizontal,
physics: NeverScrollableScrollPhysics(), // Disable manual scrolling
itemCount: loopedItems.length,
itemBuilder: (context, index) {
return loopedItems[index];
},
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment