Last active
March 7, 2025 16:24
-
-
Save Muhammad-Haris-2/f109ca363f51f1bdfa605d222ce4e5df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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